I'm new to javascript and I have a question about promise chaining. I have two promises and want to return a promise that executes P2 after P1 regardless of whether P1 succeeded or failed, and return a Promise<number>
as per P2.
So for something like this:
async function P1() : Promise<void> {
console.log("P1");
}
async function P2() : Promise<number> {
console.log("P2");
return 1;
}
function chained() : Promise<number> {
// Something here!
}
chained().then( (x) => {console.log(x);} )
The expected output should be:
[LOG]: "P1"
[LOG]: "P2"
[LOG]: 1
As far as I can tell, I can do it like this:
P1().then(P2, P2); // <--- returns Promise<number>
This is the result I want, but it's ugly because P2 is mentioned twice. Ideally I would do it using finally
like this:
P1().finally(P2); // <--- returns Promise<void>
But this returns the type of P1 and discards P2, which is the opposite of what I want.
Is there an idiomatic way of doing this?
function chained(): Promise<number> {
return P1().catch(console.error).then(P2);
}
Insert an empty catch
to suppress any failures, then simply chain P2
. Here I'm using console.error
as the catch handler, because it seems useful, but you can also suppress it completely with () => {}
.