javascript - 依次执行一批 Promise。一旦 Promise.all 完成,进入下一批

标签 javascript node.js promise batching

我有一个包含 promise 数组的数组,每个内部数组可以有 4k、2k 或 500 个 promise。

总共有大约 60k 个 promise,我也可以使用其他值对其进行测试。

现在我需要执行 Promise.all(BigArray[0])

一旦第一个内部数组完成,我需要执行下一个 Promise.all(BigArray[1]) 等等。

如果我尝试执行 Promise.all(BigArray) 它会抛出:

fatal error call_and_retry_2 allocation failed - process out of memory

我需要按顺序执行每个 Promise,而不是并行执行,我认为这就是 Node 所做的。我不应该使用新的库,但愿意考虑答案!。

编辑:

下面是一段代码示例:

function getInfoForEveryInnerArgument(InnerArray) {
    const CPTPromises = _.map(InnerArray, (argument) => getDBInfo(argument));
    return Promise.all(CPTPromises)
        .then((results) => {
            return doSomethingWithResults(results);
        });
}
function mainFunction() {
    BigArray = [[argument1, argument2, argument3, argument4], [argument5, argument6, argument7, argument8], ....];
    //the summ of all arguments is over 60k...
    const promiseArrayCombination = _.map(BigArray, (InnerArray, key) => getInfoForEveryInnerArgument(InnerArray));

    Promise.all(promiseArrayCombination).then((fullResults) => {
        console.log(fullResults);
        return fullResults;
    })
}

最佳答案

2020 年 10 月的答案。Async/await 让它变得简短:只有 10 行代码+JSDoc。

/**
 * Same as Promise.all(items.map(item => task(item))), but it waits for
 * the first {batchSize} promises to finish before starting the next batch.
 *
 * @template A
 * @template B
 * @param {function(A): B} task The task to run for each item.
 * @param {A[]} items Arguments to pass to the task for each call.
 * @param {int} batchSize
 * @returns {Promise<B[]>}
 */
async function promiseAllInBatches(task, items, batchSize) {
    let position = 0;
    let results = [];
    while (position < items.length) {
        const itemsForBatch = items.slice(position, position + batchSize);
        results = [...results, ...await Promise.all(itemsForBatch.map(item => task(item)))];
        position += batchSize;
    }
    return results;
}

关于javascript - 依次执行一批 Promise。一旦 Promise.all 完成,进入下一批,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37213316/

相关文章:

javascript - PWA 推送通知支持 iOS 吗?

javascript - img.click() 函数数组

javascript - 如何在php中ajax成功后生成图形?

javascript - Jade 转 HTML 未定义字段

mysql - SQL 结果长度且搜索时不显示任何内容

javascript - 我可以用 Bluebird.js 做一个 "lazy" promise 吗?

javascript - 随机图像点击

node.js - WS websocket send() 作为函数

node.js - 是否仍然需要 promise MongoDB 驱动程序?

javascript - JavaScript Promise 中的 "Resolve"函数