DEV Community

Cover image for Understanding Promise vs Promise.all() in JavaScript
Vasanth S
Vasanth S

Posted on

Understanding Promise vs Promise.all() in JavaScript

In JavaScript,
Promises help handle asynchronous operation in clean and structured way. When works with multiple asynchronous tasks, managing them individually can be tricky.

Promise.all() runs a multiple promises in parallel and handle all their results together.


Promise

A Promise is an object that represents eventual completion or failure of an asynchronous operation.

It can be in one of three states

  • Pending – initial state, neither fulfilled nor rejected.
  • Fulfilled – the operation completed successfully.
  • Rejected – the operation failed.
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Success!");
        // reject("Error!");
    }, 1000);
});

promise.then(result => console.log(result))
       .catch(error => console.log(error));

//Here, a single asynchronous task is being handled.
Enter fullscreen mode Exit fullscreen mode

Promise.all() is method that takes an array of promises and returns new promise that resolves when all of the promises resolve, or rejects if any one promise rejects.

Key points:

  • Waits for all promises to finish.
  • Returns results in the same order as the input promises.
  • Fails fast if any promise rejects.
const promise1 = Promise.resolve(1);
const promise2 = new Promise(resolve => setTimeout(() => resolve(2), 1000));
const promise3 = Promise.resolve(3);

Promise.all([promise1, promise2, promise3])
       .then(results => console.log(results)) // [1, 2, 3]
       .catch(error => console.log(error));

Enter fullscreen mode Exit fullscreen mode

Feature Promise Promise.all()
Input Single async operation Array of promises
Output Result of one operation Array of all results
Rejection One promise fails, only it fails Any one promise fails, entire rejects
Use case Single async task Multiple async tasks in parallel

Top comments (0)