【问题标题】:Delaying and Throttling an array of Promises with Promise.all?使用 Promise.all 延迟和限制一系列 Promise?
【发布时间】:2017-05-16 18:54:42
【问题描述】:

我有一个端点数组,我想像这样查询: const apiList = ['/api1', '/callme', '/thisonetoo']

使用基于promise的库axios,我可以通过映射数组来动态生成promise ->

Promise.all(apiList.map(name => promiseGet(name))).then(res => ...)

这很好用……但是调用服务器太快了,一些api被拒绝了,导致整个程序混乱。

有没有办法在创建或调用下一个端点之前限制/去抖动并等待 500 毫秒?

似乎限制打开的 Promise 数量是不够的。在调用数组中的下一个 api 端点之前,我必须执行某种“睡眠”操作并稍等片刻。

【问题讨论】:

标签: javascript promise es6-promise axios


【解决方案1】:

也许可以连续调用它们?

const apiList = ['/api1', '/callme', '/thisonetoo'];

function doNext() {
  const uri = apiList.shift();
  axios.get(uri)
    .then(doNext);
}

如果您想要额外的限制,您可以在doNext 中添加setTimeout

【讨论】:

  • 这似乎很有道理,但似乎数据最终不会解析为一个数组?
  • 这只是一个例子,没有错误或额外的处理。您将需要扩展 then 处理程序以收集响应。还要验证 shift 应该只在 length > 0 上调用
【解决方案2】:

我建议在调用中添加concurrency 参数:

Promise.all(apiList.map(name => promiseGet(name), { concurrency: 10 })).then(res => ...).

您也可以使用Promise.delay(500) 让方法调用在执行前等待

【讨论】:

  • 谢谢。这是核心 api 中的 avl 还是像 Bluebird 这样的第三方承诺库?你能举一个例子来说明如何使用延迟吗?欣赏它!
猜你喜欢
  • 2017-08-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多