Categories
JavaScript Answers

How to catch errors in JavaScript promises with a first level try-catch?

Spread the love

To catch errors in JavaScript promises with a first level try-catch, we use async and await.

For instance, we write

const func = async () => {
  try {
    const asyncResult = someAsyncAction();
    const someValue = await getSomeValue();
    doSomethingWith(someValue);
    await asyncResult;
  } catch (error) {
    console.error(error);
  }
};

to define the func function.

We use await to run the promises and wait for its result.

And we use a catch block to catch any promise rejections.

error would have the rejection reason.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *