Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Handling Promise rejection with a catch while using await in JavaScript
In JavaScript, when working with async/await syntax, you need proper error handling for rejected promises. While Promise chains use .catch(), async/await functions require try-catch blocks to handle promise rejections.
Basic Promise Creation
Let's start with the fundamental syntax for creating promises:
let testPromise = new Promise((resolve, reject) => {
// perform some operation
// resolve(value) for success
// reject(error) for failure
});
Example: Promise with .then() and .catch()
Here's how traditional promise handling works with .then() and .catch() methods:
Promise Handling with .then() and .catch()
Using async/await with try-catch
When using async/await, you must wrap await calls in try-catch blocks to handle promise rejections:
async function executePromise() {
try {
// Wait for promise to resolve or reject
await somePromise();
} catch (error) {
// Handle rejected promise here
console.log('Promise rejected:', error);
}
}
Example: Error Handling with async/await
This example shows how to properly catch promise rejections using try-catch with await:
Handling Promise Rejection with try-catch and await
Example: Delayed Promise Rejection
This example demonstrates handling promises that reject after a delay, showing how await waits for the promise to settle:
Handling Delayed Promise Rejection
Click the button and wait 3 seconds to see the error handling:
Key Differences
| Approach | Error Handling | Code Style |
|---|---|---|
| Promise.then() | .catch() method | Chaining |
| async/await | try-catch block | Synchronous-like |
Conclusion
When using async/await, always wrap await calls in try-catch blocks to properly handle promise rejections. This provides cleaner, more readable error handling compared to traditional promise chains.
