我目前正在尝试模拟 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/