Skip to content

Instantly share code, notes, and snippets.

@bholloway
Created February 21, 2020 00:58
Show Gist options
  • Save bholloway/4275c9aec80508fdda74fbc2c3b90fba to your computer and use it in GitHub Desktop.
Save bholloway/4275c9aec80508fdda74fbc2c3b90fba to your computer and use it in GitHub Desktop.
Flow typed decorator for promise.all() with timing
/**
* Creates a new "outer" async function with the same signature as the given `promiseFactoryFn`.
*
* When the outer function is invoked the `promiseFactoryFn` is passed the same arguments and must return a Promise or
* array thereof.
*
* When all promises complete the `callback` is invoked with the duration of each, in milliseconds. The result of the
* promises is returned from the outer function.
*/
export const promiseAllWithTiming = <T: $ReadOnlyArray<mixed>, U: mixed>(
promiseFactoryFn: (...args: T) => Promise<U>[],
callback: (number[]) => void,
): ((...args: T) => Promise<U[]>) => async (...args: T): Promise<U[]> => {
const startTime = Date.now();
const promises = promiseFactoryFn(...args);
const durations = new Array(promises.length).fill(NaN);
return Promise.all(
promises.map((p, i) =>
p.then(v => {
durations[i] = Date.now() - startTime;
return v;
}),
),
).finally(() => callback(durations));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment