Tom O'Connell
Tom O'Connell

Reputation: 185

Returned rejected promises and onPossiblyUnhandledRejection handler in Bluebird

I'm writing a lot of code with this pattern, and a similar example can be found in Bluebird's documentation:

var promise4 = Promise.join(promise1, promise2, function (value1, value2) {
  // promise 3 needs the values resolved from promise1 and promise2
  return promise3(value1, value2);
});

My error handling is done like this:

Promise.all([
  promise4
])
.catch(function (err) {
  // handle error
});

The problem is that if promise3 gets rejected, it will trigger bluebird's onPossiblyUnhandledRejection handler because it was rejected before it was attached to any promise chain (with error handling). This results in big error messages getting printed out constantly when nothing is actually wrong.

I'm not sure what to do about this because on the one hand, the above pattern is extremely useful for constructing concurrent logic and is very easy to understand, but on the other hand I don't want to simply override onPossiblyUnhandledRejection because it could be useful if I do actually forget to handle something.

bluebird's documentation kind of addresses this issue, in a way that makes it sound as if the above pattern is an odd one:

"if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages"

My "some reason" is that I need to build highly concurrent software. Is this a fundamental flaw in how I'm approaching this kind of problem? If not, how should I resolve this without removing these warnings entirely?

Upvotes: 2

Views: 3936

Answers (1)

Esailija
Esailija

Reputation: 140230

As I commented your code works just fine without reporting unhandled rejection:

function promise3(value1, value2) {
    return Promise.reject(new Error("the error"))    
}
var promise1 = Promise.resolve();
var promise2 = Promise.resolve();
var promise4 = Promise.join(promise1, promise2, function (value1, value2) {
  // promise 3 needs the values resolved from promise1 and promise2
  return promise3(value1, value2);
});

Promise.all([promise4]).catch(function(error) {
    console.log(error.message === "the error")
});

http://jsfiddle.net/6hx0zdd2/

What's more likely is that you have forgotten a return statement somewhere which is needed to wire promises together and make chaining (and error propagation) work.

Upvotes: 1

Related Questions