提问者:小点点

限制API调用队列的速率并返回结果


我循环遍历一个数组,并使用async/await为每个成员调用API,然后将结果推入返回的另一个数组中。

// My current function
async requestForEach(repos) {
    const result = [];
    for (const repo of repos) {
        result.push(await this.doSomething(repo.value));
    }
    return result;
}

我的问题是我的价格被限制了。

(node:3184) UnhandledPromiseRejectionWarning: ThrottlingException: Rate exceeded
(node:3184) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3184) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我研究了一些选项,这个异步库似乎是最受欢迎的选项。

使用Async.Queue()。。

添加到队列中的任务被并行处理(直到并发限制)。如果所有工作人员都在进行中,则将对任务进行排队,直到有一个工作人员可用。一旦工作人员完成任务,就会调用该任务的回调。

// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
    console.log('hello ' + task.name);
    callback();
}, 2);

显然我无法从回调函数中获取回调值,那么我应该如何处理这个问题呢?


共2个答案

匿名用户

看来你想要ParallelLimit。

它接受一个接收结果的可选回调。

从医生那里。

https://caolan.github.io/async/v3/docs.html#ParallelLimit

回调函数一个可选的回调,在所有函数成功完成后运行。此函数获取一个结果数组(或对象),其中包含传递给任务回调的所有结果参数。用(错误,结果)调用。

示例:

// run 'my_task' 100 times, with parallel limit of 10

  var my_task = function(callback) { ... };
  var when_done = function(err, results) { ... };

  // create an array of tasks
  var async_queue = Array(100).fill(my_task);

  async.parallelLimit(async_queue, 10, when_done);

摘自:如何使用Async.ParallelLimit最大化(并行)运行进程的数量?

匿名用户

使用允诺。全部如下

async requestForEach(repos) {
  return Promise.all(repos.map(repo => this.doSomething(repo.value)));
}

如果调用总数达到Web server限制,则可以使用像es6-promise-pool这样的库来管理并发请求。

检查此Q和;A更多细节。