Skip to content

Instantly share code, notes, and snippets.

@jdelight
Created February 24, 2016 00:38
Show Gist options
  • Save jdelight/f5766d78cb56aedf5003 to your computer and use it in GitHub Desktop.
Save jdelight/f5766d78cb56aedf5003 to your computer and use it in GitHub Desktop.
Given an array of image URLs, returns a promise resolving with the first URL to load successfully
var loadImage = (src) => {
return new Promise(function(resolve, reject) {
var proxyImage = new Image();
proxyImage.onload = function(){
console.log('resolving', src);
resolve(src);
};
proxyImage.onerror = function(){
console.log('rejecting', src);
reject(src);
};
// todo: reject if an image takes too long to load
proxyImage.src = src;
});
}
var findImage = (images) => {
return images.reduce((acc, next) => {
return acc.then(
src => src,
() => loadImage(next)
);
}, Promise.reject());
};
var images =[
'no-image',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=250%C3%97150&w=250&h=150',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=150%C3%97150&w=150&h=150'
];
findImage(images).then(src => {
// do something with the image src
document.querySelector('.image').src = src;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment