es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
16 lines (15 loc) • 754 B
JavaScript
/**
* Adds a timeout to a promise.
* @param {Promise<T>} promise - The promise to add a timeout to.
* @param {number} ms - The timeout in milliseconds.
* @returns {Promise<T>} A promise that resolves with the original promise's result or rejects if the timeout is reached.
* @template T
* @example
* const slowPromise = new Promise(resolve => setTimeout(() => resolve('Done'), 2000));
* const result = await timeout(slowPromise, 1000).catch(e => console.log(e.message));
* // Logs: "Promise timed out after 1000ms."
*/
export function timeout(promise, ms) {
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error(`Promise timed out after ${ms}ms.`)), ms));
return Promise.race([promise, timeoutPromise]);
}