我如何执行大量的承诺?

The*_*3.0 4 javascript node.js promise es6-promise

我计划在 firebase 上运行大量查询,这些查询可能会增长到数十万甚至数百万的数量级。我一直在使用Promise.all()来解决我的大部分查询,但随着请求的增长Promise.all()似乎只是停止以随机数运行。我研究过使用,Promise.map()但我不确定并发是否能解决问题。感谢您的帮助。

下面是一个简化的示例,您可以看到它似乎只是超时而不会引发任何错误:

var promises = [];
var i = 0;
for(var x = 0; x<1000000; x++){
 const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    i += 1;
    resolve(i);
  }, 10);
});
  promises.push(promise);
}


Promise.all(promises).then((value) => {
  console.log(value)
}).catch((error) => {
  console.log("Error making js node work:" + error);
})
Run Code Online (Sandbox Code Playgroud)

Bra*_*don 14

当我需要做这样的事情时,我通常将查询分成批次。批次一一运行,但每个批次中的查询并行运行。这就是它的样子。

const _ = require('lodash');

async function runAllQueries(queries) {
  const batches = _.chunk(queries, BATCH_SIZE);
  const results = [];
  while (batches.length) {
    const batch = batches.shift();
    const result = await Promises.all(batch.map(runQuery));
    results.push(result)
  }
  return _.flatten(results);
}
Run Code Online (Sandbox Code Playgroud)

您在此处看到的类似于 map-reduce。也就是说,如果您在单个节点(例如,单个进程或虚拟机)中运行大量查询,您可能会考虑跨多个节点分布查询。如果查询的数量非常大并且查询的处理顺序并不重要,那么这可能是显而易见的。您还应该确保下游系统(即您正在查询的系统)可以处理您投入的负载。