Created
February 17, 2022 17:40
-
-
Save acutmore/a2c65de6c8102336779b5ce28023e3e4 to your computer and use it in GitHub Desktop.
utility function to take an array of promises and return an async iterator that yield results as promises settle
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
/** @param promises {Array<Promise<unknown>>} */ | |
export async function * onSettled(promises) { | |
let wake; | |
let wait = new Promise(_ => wake = _); | |
let pending = promises.length; | |
const queue = []; | |
for (const p of promises) { | |
Promise.allSettled([p]).then(([result]) => { | |
queue.push(result); | |
pending--; | |
wake(); | |
wait = new Promise(_ => wake = _); | |
}); | |
} | |
while (pending > 0) { | |
await wait; | |
while (queue.length) { | |
yield queue.shift(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment