Scott Taylor
asked on
Async / Promise Issue
I am trying to understand node/javascript async / promise features. While doing this I ran across an example that confuses me. Here is the example, and the questions are below:
From https://codeburst.io/javascript-promises-explained-with-simple-real-life-analogies-dd6908092138
1. Why create a promise for this? Isn't XMLHttpRequest already async? It makes a request, and then you feed onload a function to call when it is done.
2. onload documentation says, "to be executed when the request completes successfully". So in the example above onload is used for a resolve or a reject. If onload only fires on success how would the failure portion of the IF (line 13) every be reached?
From https://codeburst.io/javascript-promises-explained-with-simple-real-life-analogies-dd6908092138
const loadImage = url => {
return new Promise(function(resolve, reject) {
//Open a new XHR
var request = new XMLHttpRequest();
request.open('GET', url);
// When the request loads, check whether it was successful
request.onload = function() {
if (request.status === 200) {
// If successful, resolve the promise
resolve(request.response);
} else {
// Otherwise, reject the promise
reject(Error('An error occurred while loading image. error code:' + request.statusText));
}
};
request.send();
});
};
1. Why create a promise for this? Isn't XMLHttpRequest already async? It makes a request, and then you feed onload a function to call when it is done.
2. onload documentation says, "to be executed when the request completes successfully". So in the example above onload is used for a resolve or a reject. If onload only fires on success how would the failure portion of the IF (line 13) every be reached?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You are welcome.
ASKER