class promise_pool {
constructor(max) {
this.max_val = max;
}
max_val = 5;
running_pool = [];
wait_queue = [];
stop = false;
push(fn) {
this.wait_queue.push(fn);
for(let i = 0; i < Math.min(this.wait_queue.length, this.max_val-this.running_pool.length); i++) {
this.running_pool.push(this.wait_queue.shift());
}
}
run() {
let flag = 1;
while(flag || running_pool.length > 0) {
// 退出条件
if(stop) {
flag = 0;
}
let finish = Promise.race(this.running_pool);
getTask(finish);
}
}
getTask(fn) {
this.running_pool.slice(this.running_pool.indexOf(fn), 1);
if(this.wait_queue.length > 0) {
this.running_pool.push(this.wait_queue.shift());
}
}
}
const URLS = [
'地址1',
'地址2',
'地址3',
]
//请求函数
let requestFn = url => {
return new Promise(resolve => {
setTimeout(() => {
resolve(`${url}任务完成`)
}, 10000 * Math.random())
}).then(res => {
console.log(res);
console.log('________________________________');
})
}
let pool = new promise_pool(2);
URLS.forEach(item => {
pool.push(requestFn(item))
})
console