-
Notifications
You must be signed in to change notification settings - Fork 2
/
cancel.ts
107 lines (93 loc) · 2.37 KB
/
cancel.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// A signal that can be used to cancel things.
export type CancelSignalLike =
| Promise<unknown>
| AbortSignal
| CancelSignal
| {
readonly aborted: boolean
readonly reason?: any
addEventListener(type: "abort", listener: () => void): void
}
export class CancelSignal {
static deferred(): [signal: CancelSignal, cancel: (reason?: any) => void] {
let cancel!: (reason?: any) => void
return [new CancelSignal((_cancel) => (cancel = _cancel)), cancel]
}
static from(item: CancelSignalLike) {
if (item instanceof Promise) {
return new CancelSignal((cancel) => {
item.then(cancel)
})
} else {
return new CancelSignal((cancel) => {
if (item.aborted) {
cancel(item.reason)
} else {
item.addEventListener("abort", () => cancel(item.reason))
}
})
}
}
static timeout(ms: number) {
return new CancelSignal((cancel) => setTimeout(cancel, ms))
}
#isCanceled = false
#reason: unknown
readonly #promise: Promise<unknown>
constructor(executor: (cancel: (reason?: unknown) => void) => void) {
this.#promise = new Promise((resolve) => {
executor((reason) => {
if (this.#isCanceled) {
return
}
this.#isCanceled = true
this.#reason = reason
resolve(reason)
})
})
}
get aborted() {
return this.#isCanceled
}
get canceled() {
return this.#isCanceled
}
get reason() {
return this.#reason
}
addEventListener(
type: "abort",
oncanceled: ((reason: unknown) => unknown) | null | undefined,
) {
this.then(oncanceled)
}
then<T>(
oncanceled: ((reason: unknown) => T) | null | undefined,
): CancelSignal {
return new CancelSignal((cancel) => {
this.#promise.then(oncanceled).then(cancel)
})
}
toAbortSignal() {
const controller = new AbortController()
this.then((reason) => controller.abort(reason))
return controller.signal
}
makeCancelable<T>(promise: PromiseLike<T>): Promise<
| {
canceled: true
reason: unknown
value?: undefined
}
| {
canceled: false
reason?: undefined
value: T
}
> {
return new Promise((resolve) => {
promise.then((value) => resolve({ canceled: false, value }))
this.then((reason) => resolve({ canceled: true, reason }))
})
}
}