【发布时间】:2017-10-22 17:00:42
【问题描述】:
我正在尝试为对 api 的 get 请求数组创建一个异步队列,我只是不确定如何组合和使用响应。也许我的实现是错误的,因为我在 promise then 函数中使用 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)
})
})
【问题讨论】:
标签: javascript node.js express asynchronous request