user3835653 user3835653 - 5 months ago 10
Node.js Question

How to have a variable number of Bluebird Promises? (Nodejs)

I have an empty array of documents.

let arrayOfDocuments = [];


I want to call http requests (using superagent) to download a text file and put its contents into my arrayOfDocuments.

request.get('docs.google.com/document/d/SOME_FILE_NAME').then((res) => {
arrayOfDocuments.push(res.text);
});


That part I get, but here is the tricky part. I want to put this in a for loop and do something after the for loop. So like:

for (let i = 0; i < numOfLinks; i++) {
// send the http requests as above
}

//do stuff here but only after the above for loop is finished.


How do I only do the last line if the loop is finished? The way my program is running right now, the code after the for loop runs before the http requests get a response and finish. I think there is a way to do this using Bluebird Promises, but I'm not sure. Thanks!

Answer

Use promise all as shown here http://bluebirdjs.com/docs/api/promise.all.html

In practice is might looks something like

var promises = []
var links = ['a.com/a', 'a.com/b']

for (let i = 0; i < links.length; i++) {
    promises.push(request.get(links[i])
}

Promise.all(promises).then(function(allRes) {
    //do anything you want with allRes or iterate
    for (var promise in promises){
      promise.then(function(singleRes){/*do something with each promise after all resolve*/}
    }
});