-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7-promise.js
More file actions
94 lines (78 loc) · 1.85 KB
/
7-promise.js
File metadata and controls
94 lines (78 loc) · 1.85 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
84
85
86
87
88
89
90
91
92
93
94
'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.emit('done', value);
return this;
}
reject(value) {
this.value = value;
this.emit('fail', value);
return this;
}
promise() {
return new Promise((resolve, reject) => {
this.on('done', (value) => resolve(value));
this.on('fail', (error) => reject(error));
});
}
}
// 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;
};
(async () => {
try {
const value = await getPerson(10).promise();
console.log('Resolved p1', value);
} catch (e) {
console.log('Rejected p1', e.message);
}
try {
const value = await getPerson(20).promise();
console.log('Resolved p2', value);
} catch (e) {
console.log('Rejected p2', e.message);
}
})();