Created
July 5, 2024 17:54
-
-
Save yuriuliam/4c8645694364269d1f4c2ca5e82f1ec7 to your computer and use it in GitHub Desktop.
run Promise.all while being aware of the current progress
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
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