AppDividend
Latest Code Tutorials

Javascript Promise.all() Method | Javascript Promise All Example

0

Javascript Promise.all() method returns the single Promise that resolves when all of the promises passed as the iterable have resolved or when an iterable contains no promises. JS Promise.all() function can be useful for aggregating the results of the multiple promises.

Promise.all takes the Async operations to a next new level as it helps you to aggregate the group of promises.

In other words, we can say that it helps you to do the concurrent operations.

Javascript Promise.all() Method

Promises in JavaScript are one of the robust APIs that help us to do the Async operations.

Promise all() method rejects with a reason for the first promise that rejects. There is no particular ordering in the execution of an array of Promises given.

On some computer systems, they may be executed in the parallel or some sense concurrently, while on the other systems, they may be executed serially.

For this unpredectible behavior of promises, there must be no dependency on any Promise on the order of execution of the Promises.

For instance, assume that you have eleven(11) promises (Async operation to perform a network call or the database connection).

In this case, you have to know when all the promises get resolved, or wait untill all the promises resolve.

So you are passing all ten promises to Promise.all. Then, Promise.all() itself as a promise will get resolved once all the ten promises get resolved or any of the ten promises get rejected with an error.

If any of the passed-in promises reject, a Promise.all() function asynchronously rejects the value of a promise that rejected, independent of what other promises have resolved or not. It has nothing to do with that.

Syntax for Promise.all() function is following.

Promise.all(iterable);

An iterable parameter is an object such as an Array or String.

Javascript Promise all() function returns one of the following values.

  1. An already resolved Promise if an iterable passed is empty.
  2. An asynchronously resolved Promise if an iterable passed contains no promises.
  3. The pending Promise in all other cases. It returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject. Returned values will be in order of the Promises passed, regardless of the complete order.

Let us take a simple example. Let us create one file called app.js and write the following code.

// app.js

const p1 = Promise.resolve(21);
const p2 = 110470116021;
const p3 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		resolve('AppDividend');
	}, 1000);
});

Promise.all([p1, p2, p3]).then(values => { 
	console.log(values);
});

Here, we have defined the three promises. Then we have set the Promise all() method to return a single promise based on three promises. In this example, all of the three promises resolves so, the Promise.all() function resolves and gives the output of all three promises in the form of an array.

The output is the following. I am using Node.js to run the file by typing the node app.

Javascript Promise All Example | Promise.all() Tutorial

Promise.all() rejects case

Let us take a scenario where one of the above promises fails to resolve.

// app.js

const p1 = Promise.resolve(21);
const p2 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		reject(new Error('rejection'));
	}, 1000);
});
const p3 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		resolve('AppDividend');
	}, 1000);
});

Promise.all([p1, p2, p3]).then(values => { 
	console.log(values);
});

In the above example, the second promise is rejected; that is why the final output will be throwing an error.

Promise.all() rejects scenario

The Promise.all()  is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all() will reject immediately.

See, we get the error like this because we have rejected one promise, and the final promise will also be rejected.

It is possible to change this behavior by handling possible rejections.

// app.js

const p1 = Promise.resolve(21);
const p2 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		reject(new Error('rejection'));
	}, 1000);
});
const p3 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		resolve('AppDividend');
	}, 1000);
});

Promise.all([
	p1.catch(error => { return error; }),
	p2.catch(error => { return error; }),
	p3.catch(error => { return error; }),
]).then(values => {
	console.log(values[0]);
	console.log(values[1]);
	console.log(values[2]);
});

In the above example, we are catching those errors inside the all() block, if any promises reject with an error, and then display the values of each promise. The output is the following.

Javascript Promise All Example

If one of the promises reject, Promise.all immediately reject, completely forgetting about the other ones on the list. Their results are ignored.

For example, if there are multiple AJAX calls, and one fails, other ones will still continue to execute, but Promise.all() won’t watch them anymore. They will probably settle, but the result will be ignored.

Promise.all does nothing to cancel them, as there’s no concept of “cancellation” in promises.

Conclusion

Javascript Promise all is the best way to aggregate a group of promises to a single promise. This is one of the ways of achieving concurrency in JavaScript.

For more information about the promise, you can read an article on the mozilla docs.

Finally, Javascript Promise All Example is over.

Recommended Posts

Promise.resolve() example

Promise.reject() example

Promise.race() example

Javascript Async / Await example

Node Async Await Example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.