With your revised code, where you're doing work prior to calling p2
, you have a few options. If you're happy for errors in the initial, synchronous part of your functino to be synchronous errors rather than promise rejections, you could just do this:
function p1(val) {
//do something with val
if (val == true)
throw err;
return p2();
}
The first part of that happens synchronously, then returns the promise from p2
. Whether you do this is partially down to what the function is doing and partially down to style. If the initial synchronous part is setting up an asynchronous operation, and you want to have the function throw (rather than return a rejected promise) when it has a problem setting up the asynchronous process (then fulfill/reject based on whether the asynchronous process worked), you might do it like this.
If you want the function to always report success/failure via a promise, then if you're doing initial work, you do need your own promise:
function p1(val) {
return new Promise((resolve, reject) => {
//do something with val
if(val == true)
reject(err);
resolve(p2());
});
}
The resolve(p2())
part resolves the promise p1
created to the promise from p2
: If p2
's promise rejects, p1
's promise rejects with the p2
rejection reason; if p2
's promise fulfills, p1
's promise fulfills with the p2
fulfillment value.
Or you might use an async
function, which has the same result:
async function p1(val) {
//do something with val
if(val == true)
throw err;
return p2();
}
In both cases, that ensures any error thrown by the initial code prior to p2
results in a rejection rather than a synchronous error, even if the initial code doesn't involve asynchronous processing.
The main thing to remember is that when you already have a promise (such as the one from p2
), there's no need to use new Promise
; instead, just chain off the promise you already have. (More here.) But when you're doing something before you get the promise, as in your revised example, you might create your own depending on whether you want the first part of your function's errors to be synchronous or promise rejections.