withTimeout

Añade un timeout a cualquier Promise, rechazándola si tarda demasiado.

#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');
}

Comparte este snippet

Comentarios