Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. const imageLoader = {
  2.  
  3. /**
  4. * Load a list of img URLs then resolve a Promise
  5. *
  6. * @param {String[]} urls images to load
  7. * @param {Number} [retries=0] number of times to retry on img.onerror
  8. * @return {Promise<HTMLImageElement[]|String>} return the loaded image elements in preserved order, or the first URL to fail on rejection
  9. */
  10. loadImages(urls, retries = 0) {
  11. return new Promise((resolve, reject) => {
  12. const images = [];
  13. Promise.all(urls.map(url => this.loadImage(url, retries)))
  14. .then(loaded => {
  15. loaded.forEach(img => {
  16. const position = urls.indexOf(img.url);
  17. images[position] = img;
  18. });
  19.  
  20. resolve(images);
  21.  
  22. }).catch(reject);
  23. });
  24. },
  25.  
  26. /**
  27. * Load an image URL then resolve a Promise
  28. *
  29. * @param {String[]} url image to load
  30. * @param {Number} [retries=0] number of times to retry on img.onerror
  31. * @return {Promise<HTMLImageElement|String>} return the loaded image element, or the URL that failed on rejection
  32. */
  33. loadImage(url, retries = 0) {
  34. return new Promise((resolve, reject) => {
  35. const img = new Image();
  36. img.onload = () => {
  37. img.url = url;
  38. resolve(img);
  39. };
  40. img.onerror = () => {
  41. retries--;
  42. if(retries >= 0) {
  43. return this.loadImage(url, retries);
  44. } else {
  45. reject(url);
  46. }
  47. };
  48. img.src = url;
  49. });
  50. }
  51. };
  52.  
  53. module.exports = imageLoader;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement