费率限制nodejs bluebird Promise.map

发布于 2025-01-30 14:52:39 字数 597 浏览 1 评论 0原文

我必须使用bluebird promise.map api在nodejs中反复致电第三方API。但是问题是API每秒仅支持20个请求。我想了解如何实现这一点。这就是我尝试的。但这给了我一个无限的循环。

let count = 0;
setInterval(() => count = 0, 1000); //reset the counter to 0 once in every second

await Promise.map(data, datum => {
  count++;

  while(count>=20){ //create an infinite loop if the count is more than 20 to wait till the count is reset. 
  }                 //The loop exits once the count value is reset to 0 by setIntercal
   
  await axios({
    url: process.env.MDNFS_URL,
    body: datum,
    method: 'POST'
  })
}, {concurrency:10})

I have to call a 3rd party API repeatedly using bluebird Promise.map API in nodeJS. But the problem is the API supports only 20 requests per second. I wanted understand how this can be implemented. This is what I tried. But it gives me an infinite loop.

let count = 0;
setInterval(() => count = 0, 1000); //reset the counter to 0 once in every second

await Promise.map(data, datum => {
  count++;

  while(count>=20){ //create an infinite loop if the count is more than 20 to wait till the count is reset. 
  }                 //The loop exits once the count value is reset to 0 by setIntercal
   
  await axios({
    url: process.env.MDNFS_URL,
    body: datum,
    method: 'POST'
  })
}, {concurrency:10})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无所谓啦 2025-02-06 14:52:39

我省略了蓝鸟,但是您几乎可以对此做完全相同的事情。

const { promisify } = require('util');
const wait = promisify(setTimeout);

function chunk(arr, size) {
  return Array.from(Array(Math.ceil(arr.length / size)), (el, i) => arr.slice(i * size, i * size + size));
}

for (let dataChunk of chunk(data, 20)) {
  await Promise.all(dataChunk.map((datum) => axios({
    url: process.env.MDNFS_URL,
    body: datum,
    method: 'POST'
  })).concat(wait(1000)))
}

I omitted bluebird, but you could pretty much do the exact same thing with it.

const { promisify } = require('util');
const wait = promisify(setTimeout);

function chunk(arr, size) {
  return Array.from(Array(Math.ceil(arr.length / size)), (el, i) => arr.slice(i * size, i * size + size));
}

for (let dataChunk of chunk(data, 20)) {
  await Promise.all(dataChunk.map((datum) => axios({
    url: process.env.MDNFS_URL,
    body: datum,
    method: 'POST'
  })).concat(wait(1000)))
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文