DEV Community

Tikam Singh Alma
Tikam Singh Alma

Posted on

2 1

Promise.all() - JavaScript Function

In simple words, a promise is a placeholder for a value that's going to be available sometime later.

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

Try it at - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Promises are useful when handling asynchoronous operations.

Promise.all() is a built-in helper that accepts an array of promises (or generally an iterable). The function returns a promise:

const allPromise = Promise.all([promise1, promise2, ...]); 
Enter fullscreen mode Exit fullscreen mode

Then you can extract promises resolved values using a then-able syntax:

allPromise.then(values => {

values; // [valueOfPromise1, valueOfPromise2, ...]

}).catch(error => {

error; // rejectReason of any first rejected promise

});
Enter fullscreen mode Exit fullscreen mode

or async/await syntax:

try {    const values = await allPromise;    
     values; // [valueOfPromise1, valueOfPromise2, ...]  
} catch (error) {    
     error;  // rejectReason of any first rejected promise  
     }
Enter fullscreen mode Exit fullscreen mode

If all promises are resolved successfully, then allPromise fulfills with an array containing fulfilled values of individual promises. The order of promises in the array does matter — you'll get the fulfilled values in that order.
But if at least one promise rejects, then allPromise rejects right away (without waiting for other promises to resolve) with the same reason.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs