Skip to content

Instantly share code, notes, and snippets.

@yuriuliam
Created July 5, 2024 17:54
Show Gist options
  • Save yuriuliam/4c8645694364269d1f4c2ca5e82f1ec7 to your computer and use it in GitHub Desktop.
Save yuriuliam/4c8645694364269d1f4c2ca5e82f1ec7 to your computer and use it in GitHub Desktop.
run Promise.all while being aware of the current progress
type OnPromiseProgressCallback = (resolvedPromises: number) => void;
/**
* Run `Promise.all` for all given promises inside an array.
* For each item complete it will call the given `onProgress` callback.
*
* NOTE: It will call the `onProgress` at the end as well, since asynchronous
* code is a mess to deal with in Javascript.
*/
const promiseAllWithProgress = async <TResult>(
values: Array<Promise<TResult>>,
onProgress: OnPromiseProgressCallback,
) => {
let resolvedPromises = 0;
const response = await Promise.all(
values.map((pending) =>
pending.then((res) => {
void setTimeout(onProgress, 1, (resolvedPromises += 1) / values.length);
return res;
}),
),
);
onProgress(1);
return response;
};
export { promiseAllWithProgress };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment