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.