Published
Edited
Jun 1, 2020
1 fork
6 stars
Insert cell
Insert cell
Insert cell
task = (i, state) =>
new Promise(async (resolve, reject) => {
state.c++;
await Promises.delay(50);
const c = state.c; // measure concurrency in the middle of the task’s run
await Promises.delay(50 + 50 * Math.random());
state.c--;
resolve(c);
})
Insert cell
Insert cell
{
const state = { c: 0 };
const results = await Promise.all(
Array.from({ length: 20 }, (_, i) => task(i, state))
);
return results;
}
Insert cell
Insert cell
{
const state = { c: 0 };
const results = await asyncPool(
4,
Array.from({ length: 20 }, (_, i) => i),
i => task(i, state)
);
return results;
}
Insert cell
Insert cell
Insert cell
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);
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more