forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhen.ts
More file actions
73 lines (68 loc) · 2.05 KB
/
Copy pathwhen.ts
File metadata and controls
73 lines (68 loc) · 2.05 KB
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
import {
$mobx,
IReactionDisposer,
Lambda,
autorun,
createAction,
fail,
getNextId
} from "../internal"
export interface IWhenOptions {
name?: string
timeout?: number
onError?: (error: any) => void
}
export function when(
predicate: () => boolean,
opts?: IWhenOptions
): Promise<void> & { cancel(): void }
export function when(
predicate: () => boolean,
effect: Lambda,
opts?: IWhenOptions
): IReactionDisposer
export function when(predicate: any, arg1?: any, arg2?: any): any {
if (arguments.length === 1 || (arg1 && typeof arg1 === "object"))
return whenPromise(predicate, arg1)
return _when(predicate, arg1, arg2 || {})
}
function _when(predicate: () => boolean, effect: Lambda, opts: IWhenOptions): IReactionDisposer {
let timeoutHandle: any
if (typeof opts.timeout === "number") {
timeoutHandle = setTimeout(() => {
if (!disposer[$mobx].isDisposed) {
disposer()
const error = new Error("WHEN_TIMEOUT")
if (opts.onError) opts.onError(error)
else throw error
}
}, opts.timeout)
}
opts.name = opts.name || "When@" + getNextId()
const effectAction = createAction(opts.name + "-effect", effect as Function)
const disposer = autorun(r => {
if (predicate()) {
r.dispose()
if (timeoutHandle) clearTimeout(timeoutHandle)
effectAction()
}
}, opts)
return disposer
}
function whenPromise(
predicate: () => boolean,
opts?: IWhenOptions
): Promise<void> & { cancel(): void } {
if (process.env.NODE_ENV !== "production" && opts && opts.onError)
return fail(`the options 'onError' and 'promise' cannot be combined`)
let cancel
const res = new Promise((resolve, reject) => {
let disposer = _when(predicate, resolve, { ...opts, onError: reject })
cancel = () => {
disposer()
reject("WHEN_CANCELLED")
}
})
;(res as any).cancel = cancel
return res as any
}