承诺链中的async.queue?

时间:2017-05-22 22:21:49

标签: javascript node.js express asynchronous request

我正在尝试为api的get请求数组创建异步队列,我只是不确定如何组合和使用响应。也许我的实现是错误的,因为我在promise中使用async.queue然后函数?

最终,我想从第一个承诺中得到结果 - >

使用第一个承诺的结果为async.queue创建一个get请求数组 - >

然后合并所有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)
    })
})

2 个答案:

答案 0 :(得分:1)

想出来,最后不得不将它包装在一个承诺中并解决q.drain()中的最终数组

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((task, callback) => {
                request({
                    method: "GET",
                    url: url,
                    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))
}

答案 1 :(得分:0)

  • 要并行启动多个异步调用,您可以使用lto
  • 要按顺序启动多个异步调用(即它们彼此依赖),您可以返回每个承诺并在Promise.all()函数中使用其结果

以下代码:

then()