One other option is to flatten your array of arrays into a single array that you can then use Promise.all()
on directly. Straight from an example on MDN, you can do that like this using .reduce()
and .concat()
:
var promises = [[promise1, promise2], [promise3,promise4], [promise5,promise6]];
Promise.all(promises.reduce(function(a, b) { return a.concat(b); }, []))
.then(function(results) {
// all done here
// results are in a flattened array
});
This solution allows the original promises array to contain either individual promises or arrays of promises or any combination of the two. It's flexible in that way and it provides the results in a single flattened array of results that are in the same order as the original promises, but are flattened into a single array. Because Promise.all()
requires that you pass it an array, the other solutions presented here require the input to be a strict array of arrays - that array cannot have any plain promises in it only arrays of promises. This solution is more flexible in that way and will accept either type of input.
For example, this will work just fine if the input happens to be like this:
var promises = [promise1, promise2, [promise3, promise4], [promise5, promise6]];
See working demo: https://jsfiddle.net/jfriend00/dLsktyyn/
Or you might find it useful to have the flatten()
function lying around for other uses:
function flatten(arr) {
return arr.reduce(function(a, b) { return a.concat(b); }, []);
}
var promises = [[promise1, promise2], [promise3,promise4], [promise5,promise6]];
Promise.all(flatten(promises)).then(function(results) {
// all done here
});
Edit
Or, Javascript arrays now have .flat()
which will flatten the array one level for you:
const promises = [[promise1, promise2], [promise3,promise4], [promise5,promise6]];
Promise.all(promises.flat()).then(function(results) {
// all done here
// results are in a flattened array
});