首页 > 解决方案 > 无需等待 Promise.all 调用即可执行的函数

问题描述

我有一个多维的承诺数组,但是在executeMethod初始for循环结束并且代码到达第二个for循环和Promise.all.

executeMethod当然是一个异步函数。

const MAX_NUMBER_OF_CONCURRENT_PROMISES = 100;
const promisesArray: Promise<void>[][] = [];
let promiseArrayIndex = 0;
let innerPromiseArrayIndex = 0;

const objectsList = [......];

for (const bucketObject of objectsList) {
    if (innerPromiseArrayIndex === MAX_NUMBER_OF_CONCURRENT_PROMISES) {
      innerPromiseArrayIndex = 0;
      promiseArrayIndex++;

      promisesArray[promiseArrayIndex] = [];
    }

    promisesArray[promiseArrayIndex][innerPromiseArrayIndex] = (
      executeMethod(bucketObject)
    );
    innerPromiseArrayIndex++;
}

for (let i=0; i< promiseArrayIndex; i++) {
  await Promise.all(promisesArray[i]);
}

我希望执行仅在for (const bucketObject of objectsList)结束后发生,并且我Promise.all按每个 Promises 数组调用。

请告知我该如何解决这个问题?

标签: javascriptnode.jstypescript

解决方案


不是Promise.all执行任何操作,而是executeMethod(bucketObject)调用。在您开始等待任何事情之前,这些都在您的循环中同步发生。

要批量执行,请使用

const MAX_NUMBER_OF_CONCURRENT_PROMISES = 100;
const objectsList = [......];

for (let index = 0; index<objectsList.length; index+=MAX_NUMBER_OF_CONCURRENT_PROMISES) {
   const promisesArray: Promise<void>[] = objectsList.slice(index, index+MAX_NUMBER_OF_CONCURRENT_PROMISES).map(executeMethod);
   await Promise.all(promisesArray);
}

推荐阅读