-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.js
55 lines (46 loc) · 1.39 KB
/
tasks.js
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
export {Task};
class Task {
constructor(description, promiseFn) {
this.description=description;
this.promiseFn = promiseFn;
this.listeners={
"start": [],
"complete": [],
"fail": []
};
this.status=Task.Status.NOT_RUNNING;
}
addEventListener(eventName, fn){
this.listeners[eventName].push(fn);
}
removeEventListener(eventName, fn){
this.listeners[eventName].remove(fn);
}
dispatchEvent(event) {
for(let listener of this.listeners[event.type]) {
listener(event);
}
}
start(...args) {
this.status=Task.Status.RUNNING;
this.dispatchEvent(new CustomEvent("start"));
return new Promise((resolve, reject)=> {
this.promiseFn.apply(null, args)
.then(result => {
this.status=Task.Status.NOT_RUNNING;
this.dispatchEvent(new CustomEvent("complete"));
resolve(result);
}, error => {
this.status=Task.Status.NOT_RUNNING;
this.dispatchEvent(new CustomEvent("fail"));
reject(error);
});
});
}
}
let RUNNING=Symbol("RUNNING");
let NOT_RUNNING=Symbol("NOT RUNNING");
Task.Status={
RUNNING: RUNNING,
NOT_RUNNING: NOT_RUNNING
};