esanz91 esanz91 - 3 months ago 13
Javascript Question

Bluebird Promise: Is is possible to have multiple reject() in new Promise(function (resolve, reject)?

Example:

function multiRejectExample(){
return new Promise(function (resolve, reject){
if(statement){
console.log('statement 1');
reject(throw new Error('error'));
}
if(statement){
console.log('statement 2');
reject(throw new Error('error'));
}
});
}


I'm using bluebird. Is the above okay to do? Is it bad practice?

Also, if it rejects in the first statement, why does 'statement 2' still print out? I want to return if 'rejected', how to I do this?

Is it better to use Promise.try and then throw the error? Help! Thank you!

Answer

Is is possible to have multiple reject() in new Promise(function (resolve, reject)?

Yes, you can have multiple places that you might call reject() for a promise. This is generically true for Promises and is not just a Bluebird feature.

A promise is a one-way state machine. Once it has been rejected with a reason, it will NOT change its state again.

I'm using bluebird. Is the above okay to do? Is it bad practice?

It isn't an error to call reject() more than once on the same promise, but only the first call to reject() will be recorded and be the reason for the rejection in the promise. Subsequent calls to reject() for the same promise will be ignored.

If you know your function is done doing what it needed to do and has called reject() and no other code needs to execute in that function, then it is bad practice to just let the rest of your code continue to execute. Depending upon what that code is, it might not do any harm, but it would be a better practice to just return when you're done.

Also, if it rejects in the first statement, why does 'statement 2' still print out? I want to return if 'rejected', how to I do this?

Calling reject() does not stop your function from executing. It just changes the state of the promise. Your function still continues to execute and then after your function is done, the .then() handler for the promise will be triggered. If you want to execute no more code in your function after you call reject(), you can just use a return statement.


In your particular case, it would probably make more sense to just return after you reject if no other code needs to be run after that, but it is not necessary:

function multiRejectExample(){ 
  return new Promise(function (resolve, reject){
    if(statement){
      console.log('statement 1');
      reject(new Error('error'));
      return;
    }
   if(statement){
     console.log('statement 2');
     reject(new Error('error')); 
     return;
   }
  });
}

See example demo: http://jsfiddle.net/jfriend00/gtq49v9x/

Comments