Skip to content

Instantly share code, notes, and snippets.

@scil
Last active September 17, 2024 04:23
Show Gist options
  • Save scil/15d63220521808ba7839f423e4d8a784 to your computer and use it in GitHub Desktop.
Save scil/15d63220521808ba7839f423e4d8a784 to your computer and use it in GitHub Desktop.
Promise.all 分组化、分批化
/* 用 Promise.all 运行一组 promise。考虑到这组 promise 非常庞大,所以分成 n 个一组,
如果第一组运行无错误,则运行第二组;第二组无错误,再运行第三组。依此类推。
*/
async function runPromisesInBatches(promises, batchSize = 50,startIndex = 0) {
let results = [];
let errorIndex=null;
while (startIndex < promises.length) {
const batch = promises.slice(startIndex, startIndex + batchSize);
try {
const batchResults = await Promise.all(batch);
results.push(...batchResults);
// console.log(batchResults)
startIndex += batchSize;
} catch (error) {
errorIndex = startIndex
console.error(`Error processing batch starting at index ${startIndex}:`, error);
// 处理错误,例如记录错误信息或停止执行
break; // 停止执行,避免后续批次继续执行
}
}
return [results, errorIndex];
}
/** 以下是测试
*/
const p1 = Promise.resolve(3);
const p2 = 1337;
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("ok");
}, 100);
});
const p4 = '6';
const p5 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("wrong");
}, 100);
});
// 示例用法
const promises = [
p1,p2,p3,p4,p5,
];
runPromisesInBatches(promises, 2).then(results => {
console.log('runPromisesInBatches 执行完毕,结果为:', results[0]);
if(results[1]) console.warn('停止在了 ', results[1])
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment