Skip to content

Instantly share code, notes, and snippets.

@yowainwright
Last active November 3, 2022 20:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yowainwright/ec4013810974a20b715d2618048b5f91 to your computer and use it in GitHub Desktop.
Save yowainwright/ec4013810974a20b715d2618048b5f91 to your computer and use it in GitHub Desktop.
load images with Promises from MPJ
import loadImage from 'loadImage'
const addImg = (src) => {
const imgEl = document.createElement('img')
imgEl.src = src
document.body.appendChild(imgEl)
}
const imgArr = [
loadImage('images/cat1.jpg'),
loadImage('images/cat2.jpg'),
loadImage('images/cat3.jpg'),
]
Promise.all(imgArr)
.then(imgs => images
.forEach(img => addImg(img.src))
.catch(err => alert(err))
function loadImage(url) {
return new Promise((resolve, reject) => {
let image = new Image()
image.onload = () => resolve(image)
const msg = `Could not load image at ${url}`
image.onerror = () => reject(new Error(msg))
image.src = url
})
}
export default loadImage

Promise example with loading images 🚀

An example of Promises from MPJ, on YouTube.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment