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

[documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)を読んで、どういうふうに見てください –

答えて

0

this packageを使用するか、次のような方法でリクエスト機能を約束してください:

requestAsync = Promise.promisify(request); 

(ただし、私は二度と試したことがありません。私はRequest-Promise packegeを使ってWebスクレーパーを作ってくれました。

+0

ありがとう、私は新しいPromise(関数{})を使用しました – Mikail

関連する問題