ThePumpkinMaster
ThePumpkinMaster

Reputation: 2351

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!

Upvotes: 1

Views: 149

Answers (2)

stygma
stygma

Reputation: 523

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

In practice it might look 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*/}
    }
});

Upvotes: 2

Ram
Ram

Reputation: 144679

You can use the Promise.map method:

Promise.map(arrayOfLinks, function(link) {
  return request.get(link);
}).then(function(arrayOfDocuments) {
   // ...
});

Upvotes: 4

Related Questions