-1

I have this simple code where an async function is called. The promise is chained with .then().catch(). When the promise gets rejected, it prints Came to catch block and Async operation succeeded as expected.

async function exampleAsyncFunction() {
  try {
    const someAsyncOperationP = someAsyncOperation().then(
        () => console.log(`Came to then block`))
      .catch(() => console.log(`Came to catch block`));
    const result = await someAsyncOperationP;
    console.log('Async operation succeeded:', result);
  } catch (error) {
    console.error('Async operation failed:', error);
  }
}

async function someAsyncOperation(): Promise < number > {
  return new Promise < number > ((resolve, reject) => {
    reject(new Error('Random error occurred'));
  });
}

// Call the async function
exampleAsyncFunction();

However, if I slightly change this code to the following where I assign the promise to a const and then attach the .then().catch() to it, then I see it goes to the Async operation failed: Error: Random error occurred block and then see the Came to catch block line.

async function exampleAsyncFunction() {
  try {
    const someAsyncOperationP = someAsyncOperation();
    someAsyncOperationP.then(
        () => console.log(`Came to then block`))
      .catch(() => console.log(`Came to catch block`));
    const result = await someAsyncOperationP;
    console.log('Async operation succeeded:', result);
  } catch (error) {
    console.error('Async operation failed:', error);
  }
}

async function someAsyncOperation(): Promise < number > {
  return new Promise < number > ((resolve, reject) => {
    reject(new Error('Random error occurred'));
  });
}

// Call the async function
exampleAsyncFunction();

I expected both these blocks of code to have the same behavior. Why do we see this difference?

Yousaf
  • 27,861
  • 6
  • 44
  • 69
Pradeep Vairamani
  • 4,004
  • 3
  • 36
  • 59
  • 4
    `.then` and `.catch` don't *modify existing* Promises, they *return new ones*. Your value `someAsyncOperationP` is a different Promise entirely in the two cases. It's like the difference between saying `const foo = new Foo();` and `const foo = new Foo().someMethod();`. – Jared Smith Aug 31 '23 at 17:48
  • 1
    Got it..thank you! – Pradeep Vairamani Aug 31 '23 at 17:53
  • Adding to the first comment, in the first code example, `someAsyncOperationP` refers to the promise returned by the `catch` method which always fulfils in your code. As a result, `catch` block isn't executed. In the second code example, `someAsyncOperationP` is a rejected promise returned by the `someAsyncOperation` function, so awaiting it causes the `catch` block to execute. After that, the callback of `catch` method is executed as well. – Yousaf Aug 31 '23 at 18:13

0 Answers0