withTimeout

Add a timeout to any Promise, rejecting if it takes too long.

#async #promise #timeout #utility
export const withTimeout = <T>(
promise: Promise<T>,
ms: number,
): Promise<T> =>
Promise.race([
promise,
new Promise<T>((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms),
),
]);
// Usage
try {
const data = await withTimeout(fetch('/api/slow'), 5000);
} catch (e) {
console.error('Request timed out');
}

Share this snippet

Comments