Coding Challenge Promisifying Image Loading

A second coding challenge, on purpose harder than the first: promisify DOM image loading, then chain a real two-image slideshow out of it.

July 11, 20263 min read16 / 22Exercise

The last post promisified a browser API with data attached. This challenge promisifies one with none, image loading from post 1, and chains the result into an actual slideshow.

The Challenge

Write createImage(imagePath), a function that returns a Promise:

  • Creates a new <img> element and sets its src to imagePath
  • Once the image loads, appends it to a container and resolves with the image element itself
  • If loading fails, rejects with a real Error

Then consume it: load one image, wait two seconds, hide it, load a second image, wait two seconds, hide that one too, using the wait() helper from a couple of posts back.

JavaScript · Live Editor
Loading editor...

Try it before reading past this point.

Building createImage

The load and error events are the exact same DOM events post 1 used to explain asynchronous image loading in the first place, just wrapped in a Promise now instead of handled with a bare listener.

JavaScript · Live Editor
Loading editor...

Hit Run and the image actually appears below. Swap the path for something broken and 'Image not found' prints instead, the same resolve-on-success, reject-on-failure shape as every other promisified function in this series.

The lifecycle of a Promise: pending while the task runs, then settling exactly once into either fulfilled or rejected, a state that never changes afterward. ExpandThe lifecycle of a Promise: pending while the task runs, then settling exactly once into either fulfilled or rejected, a state that never changes afterward.

Sequencing the Slideshow

The resolved value from createImage matters here, it's the actual image element, which is exactly what's needed to hide it two seconds later. A module-level variable tracks whichever image is currently showing.

JavaScript · Live Editor
Loading editor...

Hit Run. First image loads and appears, two seconds pass, it disappears, second image loads and appears, two seconds pass, it disappears too. Six steps, two promisified functions, one flat chain, no callback inside a callback anywhere.

The Essentials

  1. A promisified function should resolve with whatever the caller will actually need afterward, here the image element itself, not just a success flag.
  2. DOM load and error events promisify the same way any other callback-based API does: resolve on success, reject with a real Error on failure.
  3. Chaining a sequence of "load, wait, hide, load, wait, hide" is just repeated .then() calls, each one returning the next step's Promise.