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:
<html>
<body>
<h2>Promise Handling with .then() and .catch()</h2>
<p id="output"></p>
<script>
let output = document.getElementById("output");
// Creating and resolving a promise
let testPromise1 = new Promise((resolve, reject) => {
resolve("The testPromise1 is resolved successfully!");
});
// Creating and rejecting a promise
let testPromise2 = new Promise((resolve, reject) => {
reject("The testPromise2 is rejected due to error!");
});
// Execute testPromise1
testPromise1.then((result) => {
output.innerHTML += result + "<br>";
});
// Execute testPromise2 with error handling
testPromise2
.then((result) => {
output.innerHTML += result;
})
.catch((error) => {
output.innerHTML += "Caught error: " + error + "<br>";
});
</script>
</body>
</html>
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:
<html>
<body>
<h3>Handling Promise Rejection with try-catch and await</h3>
<p id="output"></p>
<script>
let output = document.getElementById("output");
// Function that returns a rejected promise
let rejectedPromise = () => {
return new Promise((resolve, reject) => {
reject(new Error("Something went wrong!"));
});
};
async function executePromise() {
try {
// Wait for promise - this will throw an error
await rejectedPromise();
output.innerHTML += "This won't execute<br>";
} catch (error) {
output.innerHTML += "Caught error: " + error.message + "<br>";
}
}
executePromise();
</script>
</body>
</html>
Example: Delayed Promise Rejection
This example demonstrates handling promises that reject after a delay, showing how await waits for the promise to settle:
<html>
<body>
<h3>Handling Delayed Promise Rejection</h3>
<p>Click the button and wait 3 seconds to see the error handling:</p>
<p id="output"></p>
<button onclick="executePromise()">Execute Promise</button>
<script>
let output = document.getElementById("output");
// Promise that rejects after 3 seconds
let timerPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Promise rejected after 3 seconds"));
}, 3000);
});
};
async function executePromise() {
output.innerHTML = "Waiting for promise...<br>";
try {
// Function waits here until promise settles
await timerPromise();
} catch (error) {
output.innerHTML += "Error caught: " + error.message;
}
}
</script>
</body>
</html>
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.
