Skip to content
0

katanakit-js / useRace

Function: useRace() ​

ts
function useRace<T>(
   promise, 
   timeoutMs, 
   errorMessage?
): Promise<T>;

Defined in: src/core/services/timing.service.ts:373

Races a promise against a timeout. Clears the timer when the promise wins so the timeout rejection cannot become an unhandled rejection.

Type Parameters ​

Type ParameterDescription
TThe promise's resolved type.

Parameters ​

ParameterTypeDefault valueDescription
promisePromise<T>undefinedThe promise to race.
timeoutMsnumberundefinedTimeout in milliseconds.
errorMessagestring"Operation timed out"Error message on timeout (defaults to "Operation timed out").

Returns ​

Promise<T>

The resolved value of the promise.

Throws ​

If the timeout fires first.

Example ​

ts
try {
  const data = await useRace(fetch("/api"), 5000);
} catch (e) {
  console.error(e); // "Operation timed out"
}

Released under the MIT License.