-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpromiseTimeout.ts
More file actions
32 lines (29 loc) · 910 Bytes
/
promiseTimeout.ts
File metadata and controls
32 lines (29 loc) · 910 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* ### promiseTimeout(promise, timeoutMs)
*
* Reject a promise if it does not resolve within `timeoutMs`.
*
* :warning: **When the timeout is hit, a promise rejection will be thrown. However,
* since promises are not cancellable, the execution of the promise itself will continue
* until it resolves or rejects.**
*
* ```js
* await flocky.promiseTimeout(Promise.resolve(1), 10)
* // -> 1
* ```
*/
export async function promiseTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
let timeoutId: NodeJS.Timeout
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => reject(new PromiseTimeoutError()), timeoutMs)
})
return Promise.race([promise, timeoutPromise]).then((result) => {
clearTimeout(timeoutId)
return result as T
})
}
export class PromiseTimeoutError extends Error {
constructor() {
super('Promise timed out')
}
}