Skip to content

Instantly share code, notes, and snippets.

@acutmore
Created February 17, 2022 17:40
Show Gist options
  • Save acutmore/a2c65de6c8102336779b5ce28023e3e4 to your computer and use it in GitHub Desktop.
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
/** @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