skip to Main Content

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


  1. 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 () => {}.

    Login or Signup to reply.
  2. If you are comfortable with using async/await you can make chained also async and then do as follows. But I’d suggest not to mix async/await and .then().catch()

    async function chained(): Promise<number> {
      try {
        await P1();
      } catch (e) {
        console.error(e);
      }
      return P2();
    }
    
    console.log(await chained());
    //OR
    chained().then(n => console.log(n));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search