-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeout.ts
32 lines (30 loc) · 982 Bytes
/
timeout.ts
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
import { Task } from ".";
/**
* reject when the execution exceeds given time
*
* @param timeout time in milliseconds
* @param fn task to run
* @param reason timeout rejection reason
*/
export default <T = any>(
timeout: number | PromiseLike<number>,
fn: Task<T> | PromiseLike<Task<T>>,
reason?: string | PromiseLike<string>,
): (() => Promise<T>) => () => Promise.all([timeout, fn, reason as any]).then(
// run the logic when task will be ready
([timeoutResolved, taskResolved, reasonResolved]) => new Promise<T>(
(resolve, reject) => {
Promise.resolve(
// task is ready, yet it may return a promise
taskResolved(),
).then(resolve, reject);
setTimeout(
() => {
// reject when the timeout is reached
reject(new Error(reasonResolved));
},
timeoutResolved,
);
},
),
);