Created
February 6, 2025 22:43
-
-
Save kvvlski/9561c9fe742ccc1787a06bad5c65f312 to your computer and use it in GitHub Desktop.
race-all.ts
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
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)]); | |
}) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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