user3835653 user3835653 - 8 months ago 24
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('').then((res) => {

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!


Use promise all as shown here

In practice is might looks something like

var promises = []
var links = ['', '']

for (let i = 0; i < links.length; 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*/}