Last active
August 29, 2015 14:02
-
-
Save wryk/993be97f25d7d860930f to your computer and use it in GitHub Desktop.
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
| // string -> Promise Image | |
| export function loadImage(url) { | |
| var image = new Image(); | |
| var promise = waitImage(image); | |
| image.src = url; | |
| return promise; | |
| } |
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
| // Image -> Promise Image | |
| export function waitImage(image) { | |
| return new Promise((resolve, reject) => { | |
| if (image.complete) { | |
| resolve(image); | |
| } else { | |
| image.addEventListener('error', handleError, false); | |
| image.addEventListener('load', handleLoad, false); | |
| } | |
| function handleError(error) { | |
| cleanup(); | |
| reject(error); | |
| } | |
| function handleLoad() { | |
| cleanup(); | |
| resolve(image); | |
| } | |
| function cleanup() { | |
| image.removeEventListener('error', handleError, false); | |
| image.removeEventListener('load', handleLoad, false); | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment