@actualwave/resolve-or-timeout
Function that runs in Promise.race() your promise and a timeout, if timeout completes first, resulting promise rejects with error.
export const resolveOrTimeout = <T = unknown>(
// Promise or a function that will be passed to a Promise object
promiseOrHandler:
| Promise<T>
| ((
resolve: (data: T) => void,
reject?: (data: unknown) => void
) => unknown),
// timeout in milliseconds. if 0, race condition will not apply and original promise will be returned as is
timeout: number,
// optional, timeout error message
timeoutError?: string,
// optional callback that will be executed when timeout completes first
onTimeout?: (msg: string) => void
) => Promise<T>;
Example
try {
/*
if request resolves in less than 500 ms, you will get response
*/
const response = await resolveOrTimeout(
fetch('/super/long/request'),
500,
'Sorry, your request takes toooooo long.',
);
} catch (error) {
/*
if request takes longer than 500 ms, promise rejects with error message
*/
}
It accepts promise or a function that will be passed to a promise.
const response = await resolveOrTimeout(
(resolve) => {
// do something then resolve
},
500
);