-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5-emitter.js
More file actions
83 lines (68 loc) · 1.74 KB
/
5-emitter.js
File metadata and controls
83 lines (68 loc) · 1.74 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
81
82
83
'use strict';
const { EventEmitter } = require('node:events');
const DEFERRED_PENDING = 0;
const DEFERRED_RESOLVED = 1;
const DEFERRED_REJECTED = 2;
class Deferred extends EventEmitter {
constructor(onDone = null, onFail = null) {
super();
this.value = undefined;
if (onDone) this.on('done', onDone);
if (onFail) this.on('fail', onFail);
this.status = DEFERRED_PENDING;
}
isPending() {
return this.status === DEFERRED_PENDING;
}
isResolved() {
return this.status === DEFERRED_RESOLVED;
}
isRejected() {
return this.status === DEFERRED_REJECTED;
}
done(callback) {
this.on('done', callback);
if (this.isResolved()) callback(this.value);
return this;
}
fail(callback) {
this.on('fail', callback);
if (this.isRejected()) callback(this.value);
return this;
}
resolve(value) {
this.value = value;
this.status = DEFERRED_RESOLVED;
this.emit('done', value);
return this;
}
reject(value) {
this.value = value;
this.status = DEFERRED_REJECTED;
this.emit('fail', value);
return this;
}
}
// Usage
const persons = {
10: 'Marcus Aurelius',
11: 'Mao Zedong',
12: 'Rene Descartes',
};
const getPerson = (id) => {
const result = new Deferred();
setTimeout(() => {
const name = persons[id];
if (name) result.resolve({ id, name });
else result.reject(new Error('Person is not found'));
}, 1000);
return result;
};
const d1 = getPerson(10)
.done((value) => console.log('Resolved d1', value))
.fail((error) => console.log('Rejected d1', error.message));
console.dir({ d1 });
const d2 = getPerson(20)
.done((value) => console.log('Resolved d2', value))
.fail((error) => console.log('Rejected d2', error.message));
console.dir({ d2 });