2016-08-04 94 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

相關問題