Async-1.js
· 667 B · JavaScript
Ham
// for use with callbacks...
import { forEachOf } from "async-es";
const images = {cat: "/cat.png", dog: "/dog.png", duck: "/duck.png"};
const sizes = {};
forEachOf(images, (value, key, callback) => {
const imageElem = new Image();
imageElem.src = value;
imageElem.addEventListener("load", () => {
sizes[key] = {
width: imageElem.naturalWidth,
height: imageElem.naturalHeight,
};
callback();
});
imageElem.addEventListener("error", (e) => {
callback(e);
});
}, err => {
if (err) console.error(err.message);
// `sizes` is now a map of image sizes
doSomethingWith(sizes);
});
1 | // for use with callbacks... |
2 | import { forEachOf } from "async-es"; |
3 | |
4 | const images = {cat: "/cat.png", dog: "/dog.png", duck: "/duck.png"}; |
5 | const sizes = {}; |
6 | |
7 | forEachOf(images, (value, key, callback) => { |
8 | const imageElem = new Image(); |
9 | imageElem.src = value; |
10 | imageElem.addEventListener("load", () => { |
11 | sizes[key] = { |
12 | width: imageElem.naturalWidth, |
13 | height: imageElem.naturalHeight, |
14 | }; |
15 | callback(); |
16 | }); |
17 | imageElem.addEventListener("error", (e) => { |
18 | callback(e); |
19 | }); |
20 | }, err => { |
21 | if (err) console.error(err.message); |
22 | // `sizes` is now a map of image sizes |
23 | doSomethingWith(sizes); |
24 | }); |