javascript - 批量发送 API 调用

标签 javascript node.js

我目前正在尝试模拟 50 万个物联网设备,以使用 nodejs 将有效负载推送到 Azure 物联网中心。由于 Node 本质上是多线程的,它的数据充斥着物联网集线器,我遇到了网络错误。

我还尝试了 async/await 方法,但将数据推送到 IoT 中心需要花费大量时间。

有没有办法只并行运行 100 个调用,等待所有调用完成,然后在 Node 中运行下一个 100 个调用?

非常感谢!

最佳答案

将批处理构建为 Promise 的嵌套数组,然后使用 Promise.all 在一个循环中的每个批处理上 await s 用于每个要解析的 Promise.all

// This is a mock request function, could be a `request` call 
// or a database query; whatever it is, it MUST return a Promise.
const sendRequest = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('request sent')
      resolve()
    }, 1000)
  })
}

// 5 batches * 2 requests = 10 requests.
const batches = Array(5).fill(Array(2).fill(sendRequest))

;(async function() {
  for (const batch of batches) {
    try {
      console.log('-- sending batch --')
      await Promise.all(batch.map(f => f()))  
    } catch(err) {
      console.error(err)
    }
  }
})()

关于javascript - 批量发送 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54359384/

相关文章:

javascript - 使用 NodeJs 自动更新网站中的元素

node.js - 如何使用 GridStore 存储具有多键 ID 的文档?

javascript - 如何在 express、couchDB 和 node.js 中使用 session

javascript - nginx + socket.io + xhr-polling 中不会触发断开连接事件

javascript - 开 Jest 返回错误: SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"' (21:0)

javascript - React - 拖动元素的 Angular 以调整内容大小

node.js - 分段上传node.js aws-sdk中的AWS s3进度条

node.js - 如何配置具有多个 session 的 Express 和 Passport

javascript - 网页滚动时滚动固定位置div(overflow y)

javascript - 从动态创建的 ajax 调用列表中读取结果