Skip to content

Instantly share code, notes, and snippets.

@meteorlxy
Last active September 28, 2020 03:44
Show Gist options
  • Save meteorlxy/09d8da0557bf9497d6539f44124dd2c9 to your computer and use it in GitHub Desktop.
Save meteorlxy/09d8da0557bf9497d6539f44124dd2c9 to your computer and use it in GitHub Desktop.
Promise.all with concurrency limit

Create n parallel runners to run Promises, to avoiding running too many Promises in the mean time with Promise.all()

const promiseAllConcurrent = async <T>(
concurrent: number,
values: readonly (() => T | PromiseLike<T>)[]
): Promise<T[]> => {
// store the resolved result
const result: T[] = [];
// next index of Promise to resolve
let nextIndex = 0;
// runner to resolve Promise of `nextIndex`
const run = async (): Promise<void> => {
if (nextIndex < values.length) {
const currentIndex = nextIndex;
nextIndex += 1;
result[currentIndex] = await values[currentIndex]();
return run();
}
};
await Promise.all(new Array(concurrent).fill(undefined).map(() => run()));
return result;
};
const timeout = (n) =>
new Promise((resolve) =>
setTimeout(() => {
console.log(`${n} resolved!`);
resolve(n);
}, n)
);
promiseAllConcurrent(2, [
() => timeout(3000),
() => timeout(1000),
() => timeout(2000),
() => timeout(4000),
() => timeout(6000),
() => timeout(5000),
]).then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment