TL;DR:
- Async operations must be awaited inside a try-catch block to handle errors.
- If it is not awaited, use
.catch()
to handle errors.- If neither is done, this will result in an unhandled promise rejection.
npm install
npm run build
Run the various test cases from VSCode debugger.
If an async operation is not awaited, and no .catch()
is used, it will result in an unhandled promise rejection.
async function unhandledPromiseRejection() {
Promise.reject(new Error('Unhandled Promise Rejection'));
}
If an async operation is awaited, the error can be caught using a try-catch
block.
async function awaitedPromiseRejection() {
try {
await Promise.reject(new Error('Awaited Promise Rejection'));
} catch (error) {
console.error(error);
}
}
If an async operation is not awaited, but a .catch()
is used, the error can be caught.
async function catchPromiseRejection() {
Promise.reject(new Error('Catch Promise Rejection')).catch((error) => {
console.error(error);
});
}