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.
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 itssrctoimagePath - 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.
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.
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.
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.
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
- A promisified function should resolve with whatever the caller will actually need afterward, here the image element itself, not just a success flag.
- DOM
loadanderrorevents promisify the same way any other callback-based API does:resolveon success,rejectwith a realErroron failure. - Chaining a sequence of "load, wait, hide, load, wait, hide" is just repeated
.then()calls, each one returning the next step's Promise.
Keep reading