并发控制
async function sleep(n, name = "test") {
return new Promise((resolve) => {
console.log("start", name, n);
setTimeout(() => {
console.log("end", name, n);
resolve(n);
}, n);
});
}
// 限制并发数 items是异步函数队列
async function asyncPool({ max, items }) {
const results = [];
const pool = new Set();
for (const item of items) {
// 避免传入的不是 Promise
const fn = async (item) => await item();
const promise = fn(item);
results.push(promise);
pool.add(promise);
// 无论执行结果是成功还是失败都清除
const clean = () => pool.delete(promise);
promise.then(clean, clean);
if (pool.size >= max) {
// 等待最快的 Promise 执行完毕,才会执行下一次 for 循环
await Promise.race(pool);
}
}
return Promise.allSettled(results);
}
async function start() {
await asyncPool({
max: 2,
items: [
() => sleep(1000, "1000"),
() => sleep(4000, "4000"),
() => sleep(3500, "3500"),
() => sleep(5000, "5000"),
() => sleep(2000, "2000"),
],
});
console.log("all done");
}
// start();
const a = Promise.allSettled([sleep(1000), sleep(2000)]);
a.then((res) => {
console.log(res);
});