javascript - 无需等待 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 数组调用。
请告知我该如何解决这个问题?
解决方案
不是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);
}
推荐阅读
- reactjs - kong 和 react js 中的混合内容 javascript 和 css 资源
- android - 使用远程调解器和分页源对具有分页 3 的存储库进行单元测试
- flutter - Flutter 中的状态管理技术?
- android - 如何防止静态字段中的上下文类引起的内存泄漏
- c++ - 这个 char* 变量指向哪里?
- google-colaboratory - /bin/bash: ./darknet: Colab 中没有这样的文件或目录错误
- android - Android:当我使用点对点 nfc 时如何防止触发光束
- javascript - 支付网关集成在 laravel 中
- vue.js - Nuxt.js 中的 Jest 全局插件
- django - 我在 django 应用程序中收集静态文件时遇到问题