Be careful with try/catch and async/await

sonht1109,promisejavascript

Sometimes try/catch and async/await may not work as we expect.

Let take an example

index.js
const promise = async () => {
  try {
    return Promise.reject("Error message");
  } catch (e) {
    console.log({ "Error catched in promise": e });
  }
};
 
(async () => {
  try {
    await promise();
  } catch (e) {
    console.log({ "Error catched in main": e });
  }
})();

We have a promise which is rejected. The error will be catched, but let's try to guess which line will catch the error.

Run file with command below

node index.js

you will see that the error is catched in main

{ 'Error catched in main': 'Error message' }

But let's change a little bit. We will add await in promise function

index.js
const promise = async () => {
  try {
    return await Promise.reject("Error message");
  } catch (e) {
    console.log({ "Error catched in promise": e });
  }
};

Run the file again and see the result

{ 'Error catched in promise': 'Error message' }

That's it. The result has changed. In real world, this case can lead to some unexpected results so just be aware all of your code lines.


Thank you for reading. Welcome all your comments/feedbacks.


© 2023 - 2024 by sonht1109