Created
April 5, 2018 21:49
-
-
Save gabemeola/27e8fd9148f9ae7541d88d54d87f5113 to your computer and use it in GitHub Desktop.
Fetches and resolves an image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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