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?
2
Answers
Insert an empty
catch
to suppress any failures, then simply chainP2
. Here I’m usingconsole.error
as the catch handler, because it seems useful, but you can also suppress it completely with() => {}
.If you are comfortable with using
async/await
you can makechained
alsoasync
and then do as follows. But I’d suggest not to mixasync/await
and.then().catch()
…