Reputation: 32130
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");
});
}
}
);
Upvotes: 0
Views: 155
Reputation: 74670
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.
Upvotes: 1