向一次只能处理20个请求的API发出多个请求

我有一个返回promise的方法,并且在内部该方法调用一个API,该API每分钟只能有20个请求。问题是我有很多对象(大约300个),并且我想为每个对象调用API。


目前,我有以下代码:


    const bigArray = [.....];


    Promise.all(bigArray.map(apiFetch)).then((data) => {

      ...

    });

但是它不处理时序约束。我希望我可以使用_.chunk和_.debounce之类的东西,lodash但是我无法解决这个问题。有人可以帮我吗?


茅侃侃
浏览 554回答 2
2回答

慕尼黑5688855

您可以每分钟发送1个包含20个请求的块,或者每3秒将其间隔1个请求(这可能是API所有者更喜欢的)。function rateLimitedRequests(array, chunkSize) {&nbsp; var delay = 3000 * chunkSize;&nbsp; var remaining = array.length;&nbsp; var promises = [];&nbsp; var addPromises = function(newPromises) {&nbsp; &nbsp; Array.prototype.push.apply(promises, newPromises);&nbsp; &nbsp; if (remaining -= newPromises.length == 0) {&nbsp; &nbsp; &nbsp; Promise.all(promises).then((data) => {&nbsp; &nbsp; &nbsp; &nbsp; ... // do your thing&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; };&nbsp; (function request() {&nbsp; &nbsp; addPromises(array.splice(0, chunkSize).map(apiFetch));&nbsp; &nbsp; if (array.length) {&nbsp; &nbsp; &nbsp; setTimeout(request, delay);&nbsp; &nbsp; }&nbsp; })();}要每3秒拨打1个电话:rateLimitedRequests(bigArray, 1);或每分钟20个:rateLimitedRequests(bigArray, 20);如果您喜欢使用_.chunk和1:_.debounce _.throttlefunction rateLimitedRequests(array, chunkSize) {&nbsp; var delay = 3000 * chunkSize;&nbsp; var remaining = array.length;&nbsp; var promises = [];&nbsp; var addPromises = function(newPromises) {&nbsp; &nbsp; Array.prototype.push.apply(promises, newPromises);&nbsp; &nbsp; if (remaining -= newPromises.length == 0) {&nbsp; &nbsp; &nbsp; Promise.all(promises).then((data) => {&nbsp; &nbsp; &nbsp; &nbsp; ... // do your thing&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; };&nbsp; var chunks = _.chunk(array, chunkSize);&nbsp;&nbsp;&nbsp; var throttledFn = _.throttle(function() {&nbsp; &nbsp; addPromises(chunks.pop().map(apiFetch));&nbsp; }, delay, {leading: true});&nbsp; for (var i = 0; i < chunks.length; i++) {&nbsp; &nbsp; throttledFn();&nbsp; }}1您可能想要,_.throttle因为它会在延迟后执行每个函数调用,而_.debounce将多个调用组合为一个调用。看到这个文章从链接的文档防抖动:把它看成是“分组多个事件之一”。试想一下,你回家,在电梯进入,门正在关闭......,突然你的邻居出现在大厅,并试图跳上电梯。要有礼貌!并打开大门,他说:你去抖动电梯离去。考虑到同样的情况可以与第三人再次发生,等等...大概推迟起飞几分钟。油门:将其视为阀门,它调节执行流程。我们能确定的时间函数可以在一定时间内被称为最大数。所以在电梯比喻..你有足够的礼貌,让在持续10秒的人,但一旦延迟的推移,你必须去!
打开App,查看更多内容
随时随地看视频慕课网APP