Skip to content

Instantly share code, notes, and snippets.

@kvvlski
Created February 6, 2025 22:43
Show Gist options
  • Save kvvlski/9561c9fe742ccc1787a06bad5c65f312 to your computer and use it in GitHub Desktop.
Save kvvlski/9561c9fe742ccc1787a06bad5c65f312 to your computer and use it in GitHub Desktop.
race-all.ts
declare global {
interface PromiseConstructor {
delay(t: number, val: any): Promise<any>;
raceAll<T, E>(
promises: Promise<T>[],
timeoutTime: number,
timeoutVal: E
): Promise<(T | E)[]>;
}
}
Promise.delay = function (t, val) {
return new Promise((resolve) => {
setTimeout(resolve.bind(null, val), t);
});
};
Promise.raceAll = function <T, E>(
promises: Promise<T>[],
timeoutTime: number,
timeoutVal: E
): Promise<(T | E)[]> {
return Promise.all(
promises.map((p) => {
return Promise.race([p, Promise.delay(timeoutTime, timeoutVal)]);
})
);
};
@kvvlski
Copy link
Author

kvvlski commented Feb 6, 2025

returns all resolved promises in a given timeout time
promises that took more time to resolve than timeout time, is replaced by timeout value
you get partial results in desired amount of time, long-running promises get rejected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment