-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy patha-deferred.js
More file actions
57 lines (48 loc) · 1.13 KB
/
a-deferred.js
File metadata and controls
57 lines (48 loc) · 1.13 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
'use strict';
class Deferred {
constructor() {
this.value = undefined;
this.error = null;
this.finished = false;
this.events = {};
}
resolve(value) {
if (this.finished) return;
this.value = value;
this.finished = true;
const event = this.events['done'];
if (event) event.forEach((fn) => fn(value));
}
reject(err) {
if (this.finished) return;
this.error = err;
this.finished = true;
const event = this.events['fail'];
if (event) event.forEach((fn) => fn(err));
}
done(fn) {
if (this.finished) return false;
const event = this.events['done'];
if (event) event.push(fn);
else this.events['done'] = [fn];
return this;
}
fail(fn) {
if (this.finished) return false;
const event = this.events['fail'];
if (event) event.push(fn);
else this.events['fail'] = [fn];
return this;
}
}
// Usage
const conferences = new Deferred()
.done((list) => {
console.log(list);
})
.fail((err) => {
throw err;
});
console.log(conferences);
conferences.resolve(['Tehran', 'Yalta', 'Potsdam']);
conferences.reject(new Error('Never occurs'));