class PromisePool {
constructor(max, fn) {
this.max = max;
this.fn = fn;
this.pool = [];
this.urls = [];
}
start(urls) {
this.urls = urls;
while (this.pool.length < this.max) {
let url = this.urls.shift();
this.setTask(url);
}
let race = Promise.race(this.pool);
return this.run(race);
}
run(race) {
race
.then(res => {
let url = this.urls.shift();
this.setTask(url);
return this.run(Promise.race(this.pool));
});
}
setTask(url) {
if (!url) return;
let task = this.fn(url);
this.pool.push(task);
console.log(`\x1B[43m ${url} 开始,当前并发数:${this.pool.length}`);
task.then(res => {
this.pool.splice(this.pool.indexOf(task), 1);
console.log(`\x1B[43m ${url} 结束,当前并发数:${this.pool.length}`);
});
}
}
const URLs = [
'bytedance.com',
'tencent.com',
'alibaba.com',
'microsoft.com',
'apple.com',
'hulu.com',
'amazon.com'
];
let dur = 0;
var requestFn = url => {
return new Promise(resolve => {
setTimeout(_ => {
resolve(`任务 ${url} 完成`);
}, 1000*dur++)
}).then(res => {
console.log('外部逻辑 ', res);
})
}
const pool = new PromisePool(3, requestFn);
pool.start(URLs);
