Skip to content

Instantly share code, notes, and snippets.

@romasan
Last active December 13, 2020 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romasan/1ba7b5164c75c7aa9c38eeb7a3b2d9c5 to your computer and use it in GitHub Desktop.
Save romasan/1ba7b5164c75c7aa9c38eeb7a3b2d9c5 to your computer and use it in GitHub Desktop.
let count = 0;
const f = (value, t = Math.floor(100 + Math.random() * 100)) => () => new Promise(resolve => {
console.log(`start: ${value} count: ${++count}`);
setTimeout(() => {
console.log(`end: ${value} count: ${--count}`);
resolve(value);
}, t);
});
const pool = [ f('A'), f('B'), f('C'), f('D'), f('E'), f('F'), f('G') ];
const promise_pool = (list, size = 10) => new Promise(resolve => {
const result = Array(list.length).fill({status: 0});
const callback = async cell => {
const next = result.findIndex(e => e.status === 0);
if (next >= 0) {
result[next] = {status: 1};
const value = await list[next]();
result[next] = {status: 2, value};
callback(cell);
} else if (result.findIndex(e => e.status === 1) < 0) {
resolve(result.map(({ value }) => value));
}
}
for (let cell = 0, length = Math.min(list.length, size); cell < length; cell++) {
callback(cell);
}
});
promise_pool(pool, 3).then(a => {console.log('done:', a)});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment