Files
flyer-crawler.projectium.com/utils/timeout.ts

24 lines
684 B
TypeScript

/**
* Wraps a promise with a timeout.
* @param promise The promise to wrap.
* @param ms The timeout duration in milliseconds.
* @returns A promise that resolves or rejects with the original promise, or rejects with a timeout error.
*/
export function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Operation timed out after ${ms / 1000} seconds`));
}, ms);
promise
.then(value => {
clearTimeout(timer);
resolve(value);
})
.catch(reason => {
clearTimeout(timer);
reject(reason);
});
});
}