Using Promise.all

Promise.all allows you to resolve an array of promises and finally resolve into an array. Also you can catch any error throwed but any of the promises with a single .catch statement.

Suppose this code:

1
2
3
4
5
6
7
8
9
10
11
foo()
.then(() => {
bar()
.then(() => {
fuzz()
.then(() => console.log('Finish'))
.catch(console.error);
})
.catch(console.error);
})
.catch(console.error);

We can make it even better as follow:

1
2
3
4
5
foo()
.then(() => bar())
.then(() => fuzz())
.then(() => console.log('Finish'))
.catch(console.error);

It’s obvious that these promises are not dependant between them, so we can handle each of them at the same time.

1
2
3
4
5
6
7
Promise.all([
foo(),
bar(),
fuzz()
])
.then(array => console.log('Finish'))
.catch(console.error);

What happen if they resolve some data?

When you use Promise.all resolves an array. Each element of that array is what the promises resolved, in the exact order. In our example we are going to make a modification to show the explanation. Assuming each function resolves some data:

1
2
3
4
5
6
7
8
9
10
11
Promise.all([
foo(),
bar(),
fuzz()
])
.then(array => {
console.log('Data from foo()',array[0]);
console.log('Data from bar()',array[1]);
console.log('Data from fuzz()',array[2]);
})
.catch(console.error);

As you can see, each function resolves its own data in a element of the resolved array. It’s simple and fun.

Loops

You have a loop, but you need to make something async inside it. Ok, take a look at this code:

1
2
3
4
5
6
7
const promises = [];

for(let i=0; i<100; i++) promises.push(foo(i));

Promise.all(promises)
.then(() => console.log('Finish'))
.catch(console.error);

References