此方法用于减轻服务器瞬时的压力负担,将多个接口分批次请求
文章来源:https://uudwc.com/A/db5kg
如果遇到耗时长的任务,用 race 等待任何一个 promise 执行完
// 定义一个异步函数 asyncPool,用于限制并发执行 Promise 数组中的任务
const asyncPool = async (poolLimit, argsArray) => {
const results = []; // 存储每个 Promise 的结果
const executing = []; // 存储当前正在执行的 Promise
// 遍历传入的 Promise 数组
for (const item of argsArray) {
results.push(item); // 将当前 Promise 添加到结果数组中
// 创建一个新的 Promise,用于表示当前执行的 Promise 完成后从 executing 数组中移除
let newPromise = item.then(() => executing.splice(0, 1));
console.log('newPromise', newPromise); // 输出新创建的 Promise
executing.push(newPromise); // 将当前执行的 Promise 添加到执行数组
// 如果执行数组中的 Promise 数量达到指定的并发限制 poolLimit
if (executing.length >= poolLimit) {
await Promise.race(executing); // 等待任何一个 Promise 完成,以控制并发
}
}
return Promise.allSettled(results); // 返回所有 Promise 的结果
};
时小记,终有成。文章来源地址https://uudwc.com/A/db5kg