I wrote a small function that checks if an image or multiple images are loaded. For that purpose, I decided to use ES6 promises, but I'm not really sure if my way of handling errors is the best way.
const loadImg = function loadImg(src) {
'use strict';
const paths = Array.isArray(src) ? src : [src];
const promise = [];
paths.forEach((path) => {
promise.push(new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({
path,
status: 'ok',
});
};
// Call `resolve` even if the image fails to load. If we were to
// call `reject`, the whole "system" would break
img.onerror = () => {
resolve({
path,
status: 'error',
});
};
img.src = path;
}));
});
return Promise.all(promise);
};
// Usage
loadImg([
'IMG.png',
'IMG.jpg',
'IMG.jpg',
'IMG.jpg',
]).then(function(e) {
console.log(e);
});
It works, but I'm worried that using objects as error messages rather than reject
has some disadvantages that I'm not aware of (e.g. potential memory leaks or people don't expect to see errors in then()
)? Is there any way I can improve this function?
reject()
on error? \$\endgroup\$