简体   繁体   中英

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,

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM