Last active
January 25, 2021 15:05
Drain an array of potential promises with a max concurrency factor
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
/** @typedef {() => Promise<unknown>} Task */ | |
/** | |
* @param {Task[]} pending | |
* @param {number} max | |
* @returns {Promise<unknown[]>} | |
*/ | |
export function drain (pending, max) { | |
return new Promise((resolve, reject) => { | |
let nextIndex = 0 | |
/** @type {Map<number, Promise<unknown>>} */ | |
const inProgress = new Map() | |
/** @type {unknown[]} */ | |
const complete = [] | |
/** @type {Error | undefined} */ | |
let firstError | |
next(max) | |
function finish () { | |
if (firstError) { | |
reject(firstError) | |
} else { | |
resolve(complete) | |
} | |
} | |
/** @param {number} [amount=1] */ | |
function next (amount = 1) { | |
if (pending.length === 0 && inProgress.size === 0) { | |
finish() | |
return | |
} | |
if (inProgress.size < max && pending.length > 0) { | |
const callbacks = pending.slice(0, amount) | |
pending.splice(0, amount) | |
callbacks.forEach(cb => { | |
const promise = cb() | |
const currentIndex = nextIndex | |
nextIndex++ | |
inProgress.set(currentIndex, promise) | |
promise | |
.then(v => { | |
complete[currentIndex] = v | |
}) | |
.catch(e => { | |
if (!firstError) { | |
firstError = e | |
} | |
}) | |
.finally(() => { | |
inProgress.delete(currentIndex) | |
next() | |
}) | |
}) | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment