Open Rain120 opened 2 years ago
function asyncPool(list, callback, limit) {
const promises = [];
const executing = [];
let i = 0;
const enqueue = () => {
if (i === list.length) {
return Promise.resolve();
}
const task = list[i++];
const p = Promise.resolve().then(() => {
return callback && callback(task, i);
});
promises.push(p);
const e = p.then(() => {
const eIndex = executing.indexOf(e);
if (eIndex > -1) {
executing.splice(eIndex, 1);
}
});
executing.push(e);
let r = Promise.resolve();
if (executing.length >= limit) {
r = Promise.race(executing);
}
return r.then(() => enqueue());
}
return enqueue().then(() => Promise.all(promises));
}
题目