Open In App
Related Articles

How to handle errors in Promise.all ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will see how to handle errors with promise.all( ) function. When working with Promise. all in JavaScript, it’s essential to handle errors properly to ensure your application’s robustness and reliability. Promise.all is all or nothing. It resolves once all promises in the array are resolved, or rejected as soon as one of them is rejected. In other words, it either resolves with an array of all resolved values or rejects with a single error. If any of the promises within the array is rejected, the Promise.all itself will reject. Here’s how you can handle errors in Promise. all.

Using .then() and .catch() Method

The .then() method can be used to define what should happen when a Promise successfully resolves, allowing you to specify the next steps in your code. The .catch() method can be utilized when a Promise encounters an error or is rejected, .catch() is employed to handle the error gracefully, letting you manage and log the error that occurred.

Syntax

const tasks = [processData(), saveData(), fetchData()];
Promise.all(tasks)
.then((completedTasks) => {

// All tasks completed successfully, handle the results here
})
.catch((error) => {

// An error occurred while performing the tasks, handle it here
});

Example: In this example, we can handle errors by chaining .then() and .catch() methods to your Promise.all call.

Javascript

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data 1');
        }, 1000);
    });
}
  
function saveData(processedData) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(`Saved`);
        }, 500);
    });
}
  
const promises = [fetchData(), saveData()];
  
Promise.all(promises)
    .then((results) => {
        console.log('All tasks completed successfully:');
        console.log(results);
    })
    .catch((error) => {
        console.error('An error occurred:', error);
    });

                    

Output:

All tasks completed successfully:
[ 'Data 1', 'Saved' ]

Using async/await

Async/await is a programming technique that streamlines asynchronous operations, allowing code to pause and resume tasks .It also simplifies asynchronous programming, by handling tasks one step at a time, enhancing code readability and responsiveness.

Syntax

async function executeTasks(tasks) {
try {
const taskResults = await Promise.all(tasks);

// Handle the successful completion of tasks here
} catch (taskError) {

// Handle errors that occurred during task execution here
}
}
const tasks = [fetchData(), saveData()];
executeTasks(tasks);

Example: In this example, we will implement a code to handle errors by using async/await syntax.

Javascript

async function handlePromises(promises) {
    try {
        const results = await Promise.all(promises);
        console.log('Successful results:', results);
    } catch (error) {
        console.error('Error occurred:', error);
    }
}
  
function fetchData() {
    return new Promise((resolve) =>
        setTimeout(() => resolve('Data Fetched'), 1000));
}
  
function saveData() {
    return new Promise((resolve) =>
        setTimeout(() => resolve('Data Saved'), 500));
}
  
const promises = [fetchData(), saveData()];
handlePromises(promises);

                    

Output:

Successful results: [ 'Data Fetched', 'Data Saved' ]


Last Updated : 08 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads