Ben Ben - 1 year ago 201
Node.js Question

Node.js - Continue promise chain for each result after promise.all()

I am using

within a promise chain. Each promise within the Promise.all() returns a string.

The issue im having is that Promise.all() returns a Promise object to the next promise and I would like to continue the promise chain for each string.

Heres an example:

return Promise.all(plugins);

.then(function(response) {


looks like:

[ 'results from p1', 'results from p2' ]

Is there any way to continue the promise chain for each of the results rather than continuing with a single object containing all results?

Answer Source

Promise.all(), by its design returns a single promise who's resolved value is an array of resolved values for all the promises you passed it. That's what it does. If that isn't what you want, then perhaps you are using the wrong tool. You can process the individual results in a number of ways:

First, you can just loop over the array of returned results and do whatever you want to with them for further processing.

Promise.all(plugins).then(function(results) {
    return {
        // can return either a value or another promise here
        return ....
}).then(function(processedResults) {
    // process final results array here

Second, you could attach a .then() handler to each individual promise BEFORE you pass it to Promise.all().

// return new array of promises that has done further processing
// before passing to Promise.all()
var array = {
    return p.then(function(result) {
        // do further processing on the individual result here
        // return something (could even be another promise)
        return xxx;

Promise.all(array).then(function(results) {
    // process final results array here

Or, third if you don't really care when all the results are done and you just want to process each one individually, then don't use Promise.all() at all. Just attach a .then() handler to each individual promise and process each result as it happens.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download