Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created April 5, 2018 21:49
Show Gist options
  • Save gabemeola/27e8fd9148f9ae7541d88d54d87f5113 to your computer and use it in GitHub Desktop.
Save gabemeola/27e8fd9148f9ae7541d88d54d87f5113 to your computer and use it in GitHub Desktop.
Fetches and resolves an image
/**
* Fetches image and returns promise after fetch.
*
* @param {string} imageUrl - Image SRC to fetch
* @return {Promise} Returns promise of imageUrl that was successful
*/
export default function fetchImage(imageUrl) {
return new Promise((resolve, reject) => {
if (imageUrl == null) {
reject('Image is null or undefined', imageUrl);
return;
}
// Create New Image
const downloadImage = new Image();
downloadImage.onload = () => {
// Resolve and return imageUrl once loaded.
resolve(imageUrl);
};
downloadImage.onerror = (err) => {
// Reject and return error and imageUrl if error.
reject(err, imageUrl);
};
// Start the Download.
downloadImage.src = imageUrl;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment