简体   繁体   English

Javascript Promise.all()在函数完成之前执行,node.js请求库

[英]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: 我使用node js request,向另一个站点发出请求,因此该请求是asyncronis函数,我需要在完成所有操作后执行代码,但由于某种原因Promise.all()在执行之前,这里是代码:

          // 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, 所以我的问题是Promise.all()中的代码行由于某种原因在执行之前

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). (但是,我从未尝试过第二次。我使用Request-Promise packege制作了Web抓取工具,效果很好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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