-
Notifications
You must be signed in to change notification settings - Fork 5
/
execute.ts
76 lines (67 loc) · 1.72 KB
/
execute.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import {AbortError} from './AbortError';
/**
* Similar to `new Promise(executor)`, but allows executor to return abort
* callback that is called once `signal` is aborted.
*
* Returned promise rejects with `AbortError` once `signal` is aborted.
*
* Callback can return a promise, e.g. for doing any async cleanup. In this
* case, the promise returned from `execute` rejects with `AbortError` after
* that promise fulfills.
*/
export function execute<T>(
signal: AbortSignal,
executor: (
resolve: (value: T) => void,
reject: (reason?: any) => void,
) => () => void | PromiseLike<void>,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (signal.aborted) {
reject(new AbortError());
return;
}
let removeAbortListener: (() => void) | undefined;
let finished = false;
function finish() {
if (!finished) {
finished = true;
if (removeAbortListener != null) {
removeAbortListener();
}
}
}
const callback = executor(
value => {
resolve(value);
finish();
},
reason => {
reject(reason);
finish();
},
);
if (!finished) {
const listener = () => {
const callbackResult = callback();
if (callbackResult == null) {
reject(new AbortError());
} else {
callbackResult.then(
() => {
reject(new AbortError());
},
reason => {
reject(reason);
},
);
}
finish();
};
signal.addEventListener('abort', listener);
removeAbortListener = () => {
signal.removeEventListener('abort', listener);
};
}
});
}