AsyncAction.js
2.31 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
74
75
76
77
78
79
80
import { Action } from './Action';
export class AsyncAction extends Action {
constructor(scheduler, work) {
super(scheduler, work);
this.scheduler = scheduler;
this.work = work;
this.pending = false;
}
schedule(state, delay = 0) {
if (this.closed) {
return this;
}
this.state = state;
const id = this.id;
const scheduler = this.scheduler;
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, delay);
}
this.pending = true;
this.delay = delay;
this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
return this;
}
requestAsyncId(scheduler, id, delay = 0) {
return setInterval(scheduler.flush.bind(scheduler, this), delay);
}
recycleAsyncId(scheduler, id, delay = 0) {
if (delay !== null && this.delay === delay && this.pending === false) {
return id;
}
clearInterval(id);
return undefined;
}
execute(state, delay) {
if (this.closed) {
return new Error('executing a cancelled action');
}
this.pending = false;
const error = this._execute(state, delay);
if (error) {
return error;
}
else if (this.pending === false && this.id != null) {
this.id = this.recycleAsyncId(this.scheduler, this.id, null);
}
}
_execute(state, delay) {
let errored = false;
let errorValue = undefined;
try {
this.work(state);
}
catch (e) {
errored = true;
errorValue = !!e && e || new Error(e);
}
if (errored) {
this.unsubscribe();
return errorValue;
}
}
_unsubscribe() {
const id = this.id;
const scheduler = this.scheduler;
const actions = scheduler.actions;
const index = actions.indexOf(this);
this.work = null;
this.state = null;
this.pending = false;
this.scheduler = null;
if (index !== -1) {
actions.splice(index, 1);
}
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, null);
}
this.delay = null;
}
}
//# sourceMappingURL=AsyncAction.js.map