created at 2023/08/03 03:50:21
updated at 2023/08/03 03:50:30
TypeScript
let idArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let request = async function (id: unknown) {
const id_1 = await new Promise((resolve, reject) => {
//随机一个执行时间
let time = Math.floor(10000 * Math.random());
console.log(`id为${id}开始请求,预计执行时间${time / 1000}`);
setTimeout(() => {
resolve(id);
}, time);
});
console.log(`id为${id_1}的请求进行逻辑处理`);
return id_1;
};
async function run() {
const pool: any = [];
// 控制任务并行数量
const max = 1;
for (let i = 0; i < idArray.length; i++) {
let promise = request(idArray[i]);
promise.then((res) => {
console.log(`id${res}的请求已经处理完毕,当前并发为${pool.length}`);
pool.splice(pool.indexOf(promise), 1);
});
pool.push(promise);
//这里是重点,当满了就阻塞
if (pool.length == max) {
await Promise.race(pool);
}
}
}