【问题标题】:async.queue within a promise chain?承诺链中的异步队列?
【发布时间】: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


    【解决方案1】:
    • 要并行启动多个异步调用,您可以使用Promise.all()
    • 要按顺序启动多个异步调用(即它们相互依赖),您可以返回每个 Promise 并在 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
      });
    

    【讨论】:

    • 嘿,谢谢,但最初当我尝试使用 promise.all 时,我从 api iwas usini 获得了速率限制,所以我需要 async.queue 之类的东西,或者我可以用 Promise 调整什么.all 来模仿?我需要能够在 promise.all 中完成 10 次,然后再完成 10 次,以此类推
    【解决方案2】:

    想通了,最终不得不将它包装在一个承诺中并在 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))
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      相关资源
      最近更新 更多