Preference to discard or reject as a result of a failed promise asynchronously

I have a Bluebird promise that wraps an AJAX request and requires rejecting the promise when the request fails. I would like to indicate the reason why the request failed, mainly from the status code, to any catch blocks that can be attached. For this I have UnauthorizedErrorand NotFoundErrorand similar classes, all extending Errorto work with matching template Bluebird catch.

The part I'm not sure about is whether I should throwor call the rejection handler. My code looks something like this:

class Request {
  // other methods

  send(method, url, args, body) {
    return new Promise((res, rej) => {
      let xhr = new XMLHttpRequest();
      xhr.open(method, url);

      xhr.onload = () => {
        res(JSON.parse(xhr.responseText));
      };

      xhr.onerror = () => {
        let status = xhr.status;
        switch (status) {
          case 401:
            // Should I use throw:
            throw new UnauthorizedError(url);
            // or
            rej(new UnauthorizedError(url));
        }
      };

      xhr.send();
    });
  }
}
+4
source share
1 answer

Inside the constructor Promise

- , - , , :

new Promise(function(resolve, reject){
     setTimeout(function(){
         // NEVER throw here, it'll throw globally and not reject the promise
     }, 100);
});

API promises, , promises, , ( ).

then

. throw then, . , , , return, .

, Angular 1.x $q, - ( throw , ).

, promises. promises , - API promises :

class Request {
    // other methods

    send(method, url, args, body) {
        return new Promise((res, rej) => {  // it good that new Promise is the first
            let xhr = new XMLHttpRequest(); // line since it throw-safe. This is why it
            xhr.open(method, url);          // was chosen for the API and not deferreds

            xhr.onload = () => {
                // This _needs_ a try/catch, it will fail if responseText
                // is invalid JSON and will throw to the global scope instead of rejecting
                res(JSON.parse(xhr.responseText));
            };

            xhr.onerror = () => {
                let status = xhr.status;
                switch (status) {
                case 401:
                    // this _must_ be a reject, it should also generally be surrounded
                    // with a try/catch
                    rej(new UnauthorizedError(url));
                }
            };

            xhr.send(); // it important that this is in the promise constructor
        });
    }
}
+6

All Articles