2017-05-22 5 views
1

私はapiへのgetリクエストの配列のための非同期キューを作成しようとしていますが、私はそのレスポンスをどのように組み合わせて使用​​するか分かりません。おそらく私の実装は間違っています。なぜなら私は約束の中で関数async.queueを使用しているからです。約束内のasync.queue?

最終的に私は最初の約束から結果を取得したいと思い - >

async.queueに対するGETリクエストの配列を作成するために、その最初の約束の使用結果 - >

は、すべての結果を結合応答を得る。私は、APIのレート制限のため、一度に外出するリクエストの量を抑える必要があります。

const rp = require("request-promise"); 
app.get("/", (req,res) => { 
    let arr = [] 
    rp.get(url) 
    .then((response) => { 
     let arrayID = response 
     let q = async.queue((task, callback) => { 
      request({ 
       method: "GET", 
       url: url, 
       qs: { 
        id: task.id 
       } 
      }, (error, response, body) => { 
       arr.push(body) 
       console.log(arr.length) 
       // successfully gives me the response i want. im trying to push into an array with all of my responses, 
       // but when i go to next then chain it is gone or if i try to return arr i get an empty [] 
      }) 
      callback() 
     }, 3) 
     for(var i = 0; i < arrayID.length; i++){ 
      q.push({ id : arrayID[i]}); 
     } 
     q.drain = function() { 
      console.log('all items have been processed'); 
     } 
     return arr 
    }) 
    .then((responseArray) => { 
     //empty array even though the length inside the queue said other wise, i know its a problem with async and sync actions but is there a way to make the promise chain and async queue play nice? 
     res.json(responseArray) 
    }) 
}) 

答えて

0
  • あなたが複数の非同期を起動するにはPromise.all()
  • を使用することができ、並列で複数の非同期呼び出しを起動するには、各約束を返し、then()関数の内部でその結果を使用することができます(すなわち、それらは相互に依存)を順次呼び出し、以下

コード:

app.get("/", (req,res) 
    .then(function(firstResult)) { 
    //You can use result of first promise here 
    return Promise.all([ 
     //Create array of get request here 
     //To also return firstResult just add it in the Promise.All array 
    ]); 
    }) 
    .then(function(allResults){ 
    //You can use results of all the get requests created in the previous then() 
    }) 
    .catch(function(error){ 
    //Deal with any error that happened 
    }); 
+0

)約束でそれをラップし、q.drainの最後の配列を(解決になってしまった、それを考え出しました私はasync.queueのような何かが必要だったか、それを模倣するPromise.allと微調整することができる何かがありますか?私はpromise.allで本質的に10回することができるようにする必要がありますし、次に別の10をします –

0

おかげで、しかし、最初に私はなっていたpromise.allでそれをしようとしたときにちょっと

const rp = require("request-promise"); 
app.get("/", (req,res) => { 
    rp.get(url) 
    .then((response) => { 
     let arrayID = response 
     return new Promise((resolve, reject) => { 
      var q = async.queue(function(task, callback) { 
       request({ 
        method: "GET", 
        url: diffUrl, 
        qs: { 
         id:task.id, 
        }, 
       }, (error, response, body) => { 
        arr.push(body) 
        callback(); 
       }) 
      }, 2); 

      q.drain =() => resolve(arr); 
      q.push(arrayID); 
     }) 

    }) 
    .then((response) => res.json(response)) 
    .catch((error) => res.json(error)) 
}