const results = [];
const timeout = i =>
new Promise(resolve =>
setTimeout(() => {
results.push(i);
resolve();
}, i)
).then(() => {
return i
});
const urls = [100, 500, 300, 200]
async function asyncPool(poolLimit, array, iteratorFn) {
const ret = [];
const executing = [];
for (const item of array) {
const p = Promise.resolve().then(() => iteratorFn(item, array));
ret.push(p);
const e = p.then(() => executing.splice(executing.indexOf(e), 1));
executing.push(e);
if (executing.length >= poolLimit) {
await Promise.race(executing);
}
}
return Promise.all(ret);
}
(async function main() {
await asyncPool(2, urls, timeout);
console.log(results)
})()