Link to home
Start Free TrialLog in
Avatar of Scott Taylor
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

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();
  });

};

Open in new window


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
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Scott Taylor
Scott Taylor

ASKER

Thank you.  That cleared up both of those issues that was haunting me while I was learning the area of the language.
You are welcome.