tl:dr
- In order to indicate normal completion of an operation, you return its result
return result
. - In order to indicate an exception, you
throw new Error(reason)
just like in synchronous code, promises are throw safe. - It is possible to explicitly return rejections from chains, but often unneeded.
One of the great things about promises is that they fix exception handling in asynchronous code.
Promises are not just a < buzzwords> composing sequential monadic DSL < /buzzwords> abstraction over concurrency - they are also throw safe!
Throw safety is really awesome in this regard, you can act just like ou would in sequential code:
function foo(){
if(somethingWrong){
// instead of returning normally, we throw, using the built in exception chain
// code blocks have. This indicates something unexpected breaking the sequence of cour code
throw new Error("Something was wrong");
}
return "some normal result"; // here we indicate a function terminated normally,
// and with which value.
}
Callbacks in node use the (err,result...)
convention which I find ugly. With promises, You gain the benefits of error handling you have in sequential code again:
somePromise.then(function(){
if(rejectRightAway){
throw new Error("rejecting right away...");
}
return "some normal result";
})....
See how similar it is to sequential code? Whenever you want to reject you throw
from the then handler, whenever you want to fulfill you return from the then handler. Just like in "synchronous" code.
So in your case:
//want to throw promise1 rejection //ok to just return new Error?
return new Error('promise1 rejected so through promise0 rej then mainPromise rej');
Is solved exactly with what you intuitively wanted to do:
throw new Error("promise1 rejected so through promise0 rej then mainPromise rej");