An example of Promises from MPJ, on YouTube.
Last active
November 3, 2022 20:41
-
-
Save yowainwright/ec4013810974a20b715d2618048b5f91 to your computer and use it in GitHub Desktop.
load images with Promises from MPJ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment