【发布时间】:2020-12-05 18:24:09
【问题描述】:
我正在遍历一个数组并使用 async/await 为每个成员进行 API 调用,然后我将结果推送到另一个返回的数组中。
// My current function
async requestForEach(repos) {
const result = [];
for (const repo of repos) {
result.push(await this.doSomething(repo.name));
}
return result;
}
// doSomething()
const AWS = require('aws-sdk');
const codecommit = new AWS.CodeCommit();
async doSomething(repoName){
return (await codecommit.listBranches({
repoName
}).promise()).branches;
}
我的问题是我的速率受到限制。如果我捕获并打印我得到的错误..
ThrottlingException: Rate exceeded {
// Call stack here
code: 'ThrottlingException',
time: 2020-08-16T15:52:56.632Z,
requestId: '****-****-****-****-****',
statusCode: 400,
retryable: true
}
我正在使用的 API 的文档可以在这里找到 - https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CodeCommit.html#listBranches-property
我查看了选项,this async library 似乎是最受欢迎的选项。
使用 async.queue()..
添加到队列中的任务被并行处理(直到 并发限制)。如果所有工作人员都在进行中,则任务排队 直到一个可用。一旦工人完成一项任务, 任务的回调被调用。
// create a queue object with concurrency 2 var q = async.queue(function(task, callback) { console.log('hello ' + task.name); callback(); }, 2);
显然我无法从回调函数中取回值,那么我应该如何解决这个问题?
【问题讨论】:
-
您需要按顺序拨打电话吗?还是可以进行并行调用?
-
并行调用没问题
-
不,你不需要使用 async.js(如果你还在使用它,请确保不要使用回调样式)。您的顺序迭代很好,您需要做的就是在获得
ThrottlingException时添加延迟。 -
嘿@Bergi,请您详细说明
delay部分。很想听听像您这样的专家的解决方案。它将帮助我们/其他人在类似情况下应用更好的解决方案。像Promise和setTimeout一样吗?在此先感谢???? -
@newprogrammer 您能否链接您正在使用的 API 文档以及其
ThrottlingExceptions的外观?或者分享this.doSomething方法的定义?那么也许我可以写一个量身定制的答案。
标签: javascript node.js api asynchronous async-await