Bluebird Promise.all doesn't get called

326
April 03, 2017, at 12:26 PM

I have a url which returns a list of other urls For each url, I want to do stuff and then use Promise.all to tell me that it finished.

For some reason, it does process all urls, but the Promise.all doesn't seem to be called (Bluebird)

What am I doing wrong?

var rp = require("request-promise");
var Promise = require("bluebird");
var promrequests = [];
rp(
 {
  url: url_of_list_of_urls,
  json: true,
 },
 function(error, response, body) {
  if (!error && response.statusCode === 200) {
   let urls = [];
   for (var i in body) {
    urls.push(body[i]);
   }
   for (let j in urls) {
    let url = urls[j];
    promrequests.push(
     rp(
      { url: url, followAllRedirects: true },
      function(error, response, body) {
       console.log("working on " + url);
       // do stuff
      }
     )
    );
   }
   Promise.all(promrequests).then(function() {
    console.log("finished all");
   });
  }
 }
);
Answer 1

There's no need to use callbacks with the request-promise library, the example code is a mixture of the original request callback API and the request-promise API.

Bluebird also has a .map helper to make working with arrays easier.

Dropping all the callbacks and returning promises throughout the chain gives you something like (untested):

requestOptionsUrls = {
  url: url_of_list_of_urls,
  json: true,
}
rp(requestOptionsUrls).then(function(urls){
  return Promise.map(urls, function(url){
    return rp({ url: url, followAllRedirects: true })
      .then(function(body){
        console.log("working on " + url);
        // work
      })
  })
})
.then(function(){
  console.log("finished all");
})
.catch(function(error){
  console.error(error)
})

request-promise will do 2XX checking for you unless you set the simple request option to false.

It also only resolves the body of the request unless you set the resolveWithFullResponse to true, say if you wanted to do more complex checks on the status code of the response.

READ ALSO
MEAN: NodeJS serving Angular node_modules returns index.html

MEAN: NodeJS serving Angular node_modules returns index.html

NodeJS https server running an api, cms and angular appWhen I start the server on my local machine (macOS Sierra) using nodemon everything works fine

408
findByIdAndUpdate and recalculate average temperature

findByIdAndUpdate and recalculate average temperature

I have a problem to do a query to mongo via MongooseI push a new object on my array of object and i want to update the avaerage value (of temperature field in my object in the array)

305
Mongoose: Push data to array in for loop

Mongoose: Push data to array in for loop

i have small problem i have this code:

370
Using a POST request inside a GET request's call back (Closures)

Using a POST request inside a GET request's call back (Closures)

I will demonstrate my problem with this simplified code:

226