Last active
April 29, 2021 03:37
-
-
Save magic-akari/8c04b74311f9d5576b9a1c98deeac40e 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
const promisePool = <T>(list: Iterable<() => PromiseLike<T>>, limit: number): Promise<T[]> => { | |
const result: Promise<T>[] = []; | |
const iterator = list[Symbol.iterator](); | |
return new Promise((resolve, reject) => { | |
const settle = (next: ReturnType<typeof iterator["next"]>) => { | |
if (next.done) { | |
Promise.all(result).then(resolve, reject); | |
return; | |
} | |
const value = Promise.resolve(next.value()); | |
result.push(value); | |
value.then(() => { | |
settle(iterator.next()); | |
}, reject); | |
}; | |
for (let i = 0; i < limit; i += 1) { | |
settle(iterator.next()); | |
} | |
}); | |
}; | |
const a = (n: number): Promise<number> => | |
new Promise((resolve) => { | |
setTimeout(() => { | |
console.log(n); | |
resolve(n); | |
}, n); | |
}); | |
const b = [() => a(300), () => a(500), () => a(100), () => a(300), () => a(500), () => a(100)]; | |
const c = await promisePool(b, 3); | |
console.log(c); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment