Last active
December 13, 2020 21:48
-
-
Save romasan/1ba7b5164c75c7aa9c38eeb7a3b2d9c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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