Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const imageLoader = {
- /**
- * Load a list of img URLs then resolve a Promise
- *
- * @param {String[]} urls images to load
- * @param {Number} [retries=0] number of times to retry on img.onerror
- * @return {Promise<HTMLImageElement[]|String>} return the loaded image elements in preserved order, or the first URL to fail on rejection
- */
- loadImages(urls, retries = 0) {
- return new Promise((resolve, reject) => {
- const images = [];
- Promise.all(urls.map(url => this.loadImage(url, retries)))
- .then(loaded => {
- loaded.forEach(img => {
- const position = urls.indexOf(img.url);
- images[position] = img;
- });
- resolve(images);
- }).catch(reject);
- });
- },
- /**
- * Load an image URL then resolve a Promise
- *
- * @param {String[]} url image to load
- * @param {Number} [retries=0] number of times to retry on img.onerror
- * @return {Promise<HTMLImageElement|String>} return the loaded image element, or the URL that failed on rejection
- */
- loadImage(url, retries = 0) {
- return new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => {
- img.url = url;
- resolve(img);
- };
- img.onerror = () => {
- retries--;
- if(retries >= 0) {
- return this.loadImage(url, retries);
- } else {
- reject(url);
- }
- };
- img.src = url;
- });
- }
- };
- module.exports = imageLoader;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement