@zelgadis87/utils-core 4.8.0 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@zelgadis87/utils-core",
4
- "version": "4.8.0",
4
+ "version": "4.9.0",
5
5
  "author": "Zelgadis87",
6
6
  "license": "ISC",
7
7
  "private": false,
@@ -21,3 +21,17 @@ export function promiseSequence<R>( ...fns: TFunction<void, Promise<R>>[] ): TFu
21
21
  export function delayPromise<T>( duration: TimeDuration ): TAsyncFunction<T, T> {
22
22
  return ( result: T ) => duration.promise().then( () => result );
23
23
  }
24
+
25
+ type TAwaitAtMostOutput<T> = { status: 'ok', value: T } | { status: 'timeout', value?: never };
26
+ export class TimeoutError extends Error {}
27
+ export async function awaitAtMost<T>( p: Promise<T>, t: TimeDuration ): Promise<T> {
28
+ return Promise.race<TAwaitAtMostOutput<T>>( [
29
+ p.then( value => ( { status: 'ok', value } ) ),
30
+ t.promise().then( () => ( { status: 'timeout' } ) )
31
+ ] ).then( ( { status, value } ) => {
32
+ if ( status === 'ok' )
33
+ return value;
34
+ throw new TimeoutError();
35
+ } );
36
+
37
+ }