Skip to content

Instantly share code, notes, and snippets.

@alexnoz
Last active June 11, 2020 15:57
Show Gist options
  • Save alexnoz/399ecde58a434eaf93d2585d933bbce9 to your computer and use it in GitHub Desktop.
Save alexnoz/399ecde58a434eaf93d2585d933bbce9 to your computer and use it in GitHub Desktop.
Load images asynchronously and determine when the loading is finished
const getImage = url => (
new Promise((resolve, reject) => {
const image = new Image()
image.onload = e => {
resolve(image)
}
image.onerror = e => {
reject(Error("Network Error"))
}
// image.width = 500
image.src = url
})
)
/**
* Returns image promises
* @param {String[]} images - array of urls
* @returns {Promise[]} An array of image promises
*/
const loadImages = images => (
images.map(getImage)
)
/*
Promise.all(loadImages(images))
.then() // Done callback
.catch()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment