不等待Promise的函数.所有的电话



我有一个多维数组的承诺,但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数组。

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

执行任何操作的不是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);
}

最新更新