2016-08-04 96 views
0

我使用节点js请求,向其他站点发出请求,所以请求是asyncronis函数,我需要在其全部执行后执行代码完成的,但由于某种原因Promise.all()之前执行,这里是代码:Javascript Promise.all()在函数完成之前执行,node.js请求库

  // 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); 

      }); 

,所以我的问题是,代码Promise.all行()之前执行,因为某些原因,

+3

'request()'不返回承诺。 – SLaks

+0

ops,比我应该创造一个承诺?我没有在承诺 – Mikail

+1

然后阅读一些[文档](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)的经验,看看你怎么去 –

回答

0

您应该使用this package或类似promisify请求功能这样的事情:

requestAsync = Promise.promisify(request); 

(但我从来没有尝试过第二个。我使用了Request-Promise packege来制作一个网页抓取工具,它工作得很好)。

+0

谢谢,我使用了新的Promise(函数{}) – Mikail

相关问题