strugee
strugee

Reputation: 2800

How can I resolve a Promise early in the chain?

I'm doing some HTTP calls in Node.js and want to examine whether or not the request failed or not - by this I mean that an error is not necessarily considered a "failure condition", but that I want to execute some business logic based on that. I have something similar to the following code (though obviously this is contrived since I simplified it):

let p = new Promise(function(resolve, reject) {
    // In the real implementation this would make an HTTP request.
    // The Promise resolution is either a response object or an Error passed to the `error` event.
    // The error doesn't reject because the value I'm actually interested in getting is not the response, but whether the HTTP call succeeded or not.
    Math.random() <= 0.5 ? resolve({ statusCode: 200 }) : resolve(new Error());
});

p.then(ret => { if (ret instanceof Error) return false; }) // This line should resolve the promise
 .then(/* Handle HTTP call success */);

Basically I want to say, "if I resolved to an error object, just bail out and return false. Otherwise assert some more stuff on the response object and maybe return true, maybe return false."

How can I resolve the promise early and not execute the rest of the chain? Am I thinking about this all wrong? I'm not rejecting the promise if the HTTP call errors because AFAICT you can't get a value out of .catch() (this promise eventually gets passed to Promise.all) in the same way you can with .then(), but I could be wrong.

I'm on Bluebird, FWIW, so feel free to use extra stuff from them.

Upvotes: 0

Views: 477

Answers (2)

tiagodws
tiagodws

Reputation: 1395

You can get values out of a catch(), just return them, as stated on the docs:

By not returning a rejected value or throwing from a catch, you "recover from failure" and continue the chain

That would be the best implementation ;)

Upvotes: 1

Bergi
Bergi

Reputation: 665554

Just don't use a chain here, but only a single handler:

p.then(ret => {
    if (ret instanceof Error) return false; // This line will resolve the promise
    /* else handle HTTP call success, and return true/false or another promise for it */
});

Upvotes: 0

Related Questions