Flock Dawson Flock Dawson - 1 month ago 5
Javascript Question

Use of promises in loop (node)

I'm working on a NodeJS backend service, and use promises to load any data. Now, I want to make a combination (array) of items coming from different sources. I have the following solution, but I don't think this is the right way to get around something like this.

var results = [];
loop(items, index, data, results).then(function() {
console.log(results);
});

function loop(items, index, data, results) {
return utils.getPromise(function(resolve, reject) {
if (index === items.length) {
// Stop
resolve();
} else {
doAction(items[index], data).then(function(result) {
if (result) {
mergeResults(results, result)
} else {
loop(items, index + 1, data, results).then(resolve, reject);
}
}, reject);
}
});
}

function doAction(item, data) {
return utils.getPromise(function(resolve, reject) {
item.doIt(data).then(resolve, reject);
});
}


I think the right way would be to return a promise immediately, and add results on the fly, but I don't know exactly how to do this. Any suggestions?

Answer

You could use Promise.all to gather all the results from the promises. The .all promise itself is then resolved with an array containing all the single results from each promise.

I think the right way would be to return a promise immediately

Like you suggested you would just return the promise and create an array from these promises. After the loop you give this array into Promise.all.

Might look like this:

var promiseArray = [];
for(var i=0;i<array.length;i++){
    promiseArray.push(doSomethingAsync(array[i]));
}
Promise.all(promiseArray).then(function(responseArray){
    //do something with the results
});