handling rejections in javascript
Let's explore how to handle rejections in JavaScript using both the .catch() method with Promises and the try...catch statement with async/await. We'll use a real-life example of fetching data from an API, which is a common asynchronous operation.
Handling Rejections with Promises:
function fetchData() {
return new Promise((resolve, reject) => {
// Simulating an API call
const success = Math.random() < 0.8; // 80% chance of success
setTimeout(() => {
if (success) {
resolve("Data successfully fetched");
} else {
reject("Failed to fetch data");
}
}, 1000);
});
}
// Using .catch() method
fetchData()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error("Error:", error);
});
In this example, the fetchData function returns a Promise that simulates fetching data from an API. The .then() block handles the resolved case, and the .catch() block handles the rejected case.
Handling Rejections with async/await:
async function fetchDataAsync() {
return new Promise((resolve, reject) => {
// Simulating an API call
const success = Math.random() < 0.8; // 80% chance of success
setTimeout(() => {
if (success) {
resolve("Data successfully fetched");
} else {
reject("Failed to fetch data");
}
}, 1000);
});
}
// Using async/await with try...catch
async function exampleAsyncFunction() {
try {
const result = await fetchDataAsync();
console.log(result);
} catch (error) {
console.error("Error:", error);
}
}
exampleAsyncFunction();
In this example, fetchDataAsync is an asynchronous function that returns a Promise. The exampleAsyncFunction uses async/await with a try...catch statement to handle the resolved and rejected cases.
In both examples, if the data fetching is successful, it prints the result. If there's an error (simulated by the rejection in our example), it catches the error and logs it. This is a common pattern in real-life applications when dealing with asynchronous operations, such as fetching data from APIs or handling user input.
Subscribe to my newsletter
Read articles from Piyush Agrawal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by