Harshil Chovatiya - Day 35: Handling Asynchronous Errors in Promises

Harshil Chovatiya - Day 35: Handling Asynchronous Errors in Promises.

Harshil Chovatiya - Day 35: Handling Asynchronous Errors in Promises.

Harshil Chovatiya - Day 35: Handling Asynchronous Errors in Promises

In today's lesson, we'll delve into more advanced techniques for handling asynchronous errors when working with Promises. Effective error handling is crucial for robust and reliable asynchronous code in JavaScript.

1. Handling Errors with .catch():

In Promises, you can handle errors using the .catch() method. This method is attached to a Promise and is called when the Promise is rejected. Here's an example:

                
    
function performAsyncTask() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            const error = true; // Simulate an error
            if (error) {
                reject(new Error('An error occurred.'));
            } else {
                resolve('Task completed successfully.');
            }
        }, 1000);
    });
}

performAsyncTask()
    .then(function (result) {
        console.log(`Result: ${result}`);
    })
    .catch(function (error) {
        console.error(`Error: ${error.message}`);
    });
    
    

In this example, the .catch() method is used to handle the error if the Promise is rejected. This is a concise way to catch errors in Promise chains.

2. Handling Multiple Promises Concurrently with .catch():

When working with multiple Promises concurrently, you can use .catch() with each Promise in a Promise.all() array. This allows you to handle errors from any of the concurrent Promises. Here's an example:

                
    
const promise1 = performAsyncTask(1);
const promise2 = performAsyncTask(2);
const promise3 = performAsyncTask(3);

Promise.all([promise1, promise2, promise3])
    .then(function (results) {
        console.log(`Results: ${results}`);
    })
    .catch(function (error) {
        console.error(`Error: ${error.message}`);
    });
    
    

In this example, if any of the Promises rejects, the .catch() method handles the first encountered error.

3. Rethrowing Errors:

Sometimes, you might need to rethrow errors to handle them at a higher level or to perform additional error-specific actions. You can rethrow errors within a .catch() block by returning a rejected Promise. Here's an example:

                
    
performAsyncTask()
    .then(function (result) {
        console.log(`Result: ${result}`);
    })
    .catch(function (error) {
        console.error(`Error: ${error.message}`);
        return Promise.reject(error); // Rethrow the error
    })
    .then(function () {
        console.log('This code will still run.');
    })
    .catch(function (error) {
        console.error(`Rethrown Error: ${error.message}`);
    });
    
    

In this example, the first .catch() block rethrows the error, and the subsequent .then() block is still executed. The rethrown error can be caught and handled at a higher level.

Effective error handling is essential when working with Promises to ensure that your asynchronous code is robust and reliable. With the .catch() method and rethrowing errors, you can manage and propagate errors gracefully. In the upcoming days, we'll explore more advanced topics related to asynchronous programming in JavaScript.

© 2023 Harshil Chovatiya

Social Media

Comments