-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
promises.ts
37 lines (35 loc) 路 947 Bytes
/
promises.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
33
34
35
36
37
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license.
export class TimeoutError extends Error {}
/** returns curried promise factory that */
export function promiseInterrupter({
timeout = -1,
cancel
}: {
timeout?: number;
cancel?: Promise<void>;
}): <T>(p: Promise<T>) => Promise<T> {
timeout = Number.isInteger(timeout) ? timeout : -1;
return <T>(p) =>
new Promise<T>((resolve, reject) => {
if (timeout < 0) {
p.then(resolve).catch(reject);
if (cancel) {
cancel.then(reject).catch(reject);
}
} else {
const i = setTimeout(() => {
reject(new TimeoutError());
}, timeout);
const clear = () => clearTimeout(i);
p.then(resolve)
.catch(reject)
.finally(clear);
if (cancel) {
cancel
.then(reject)
.catch(reject)
.finally(clear);
}
}
});
}