Mikail Mikail - 4 months ago 11
Node.js Question

Javascript Promise.all() executes before function is done, node.js request library

I use node js request, to make a requests to an other site, so request is asyncronis function, I need to execute a code after its all done, but for some reason Promise.all() executes before, here is the code:

// in this object I store request's promises
var tempObj = {};
for (var i = self.numberOfPaginations.length; i >= 1; i--) {

tempObj['request'+ i] = request('http://www.somewebsite.com/search/page='+i ,function (err,resp,body) {
// gets urls of listings
if (!err && resp.statusCode == 200) {

var $ = cheerio.load(body);

$('.title').each(function() {
self.urls.push($(this).attr('href'));
});

$('.info a').each(function () {
self.urls.push($(this).attr('href'));
});

// this log out puts the desired result
console.log(self.urls);

}



});



}
// this line of code pushes promises into array
Promise.all(Object.keys(tempObj).map(function (key) {return tempObj[key]})).then(function (argument) {
// this line of code executes before all the work in requests is done , however it should not!
console.log(self.urls);

});


so my problem is that the line of code in Promise.all() executes before, for some reason,

Answer

You should either use this package or sort of promisify the request function with something like this:

requestAsync = Promise.promisify(request); 

(However I never tried the second. I used Request-Promise packege to make a web scraper and it works so good).