Skip to content

Commit 42349c4

Browse files
committed
Use .on() to subscribe
1 parent 5a7a81d commit 42349c4

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

JavaScript/6-on.js

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
'use strict';
2+
3+
const { EventEmitter } = require('events');
4+
5+
const DEFERRED_PENDING = 0;
6+
const DEFERRED_RESOLVED = 1;
7+
const DEFERRED_REJECTED = 2;
8+
9+
class Deferred extends EventEmitter {
10+
constructor(onDone = null, onFail = null) {
11+
super();
12+
this.value = undefined;
13+
if (onDone) this.on('done', onDone);
14+
if (onFail) this.on('fail', onFail);
15+
this.status = DEFERRED_PENDING;
16+
}
17+
18+
isPending() {
19+
return this.status === DEFERRED_PENDING;
20+
}
21+
22+
isResolved() {
23+
return this.status === DEFERRED_RESOLVED;
24+
}
25+
26+
isRejected() {
27+
return this.status === DEFERRED_REJECTED;
28+
}
29+
30+
done(callback) {
31+
this.on('done', callback);
32+
if (this.isResolved()) callback(this.value);
33+
return this;
34+
}
35+
36+
fail(callback) {
37+
this.on('fail', callback);
38+
if (this.isRejected()) callback(this.value);
39+
return this;
40+
}
41+
42+
resolve(value) {
43+
this.value = value;
44+
this.status = DEFERRED_RESOLVED;
45+
this.emit('done', value);
46+
return this;
47+
}
48+
49+
reject(value) {
50+
this.value = value;
51+
this.status = DEFERRED_REJECTED;
52+
this.emit('fail', value);
53+
return this;
54+
}
55+
}
56+
57+
// Usage
58+
59+
const persons = {
60+
10: 'Marcus Aurelius',
61+
11: 'Mao Zedong',
62+
12: 'Rene Descartes',
63+
};
64+
65+
const getPerson = id => {
66+
const result = new Deferred();
67+
setTimeout(() => {
68+
const name = persons[id];
69+
if (name) result.resolve({ id, name });
70+
else result.reject(new Error('Person is not found'));
71+
}, 1000);
72+
return result;
73+
};
74+
75+
const d1 = getPerson(10);
76+
d1.on('done', value => console.log('Resolved d1', value));
77+
d1.on('fail', error => console.log('Resolved d1', error));
78+
console.dir({ d1 });
79+
80+
const d2 = getPerson(20);
81+
d2.on('done', value => console.log('Resolved d2', value));
82+
d2.on('fail', error => console.log('Resolved d2', error.message));
83+
console.dir({ d2 });

0 commit comments

Comments
 (0)