-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1-object.js
More file actions
47 lines (39 loc) · 775 Bytes
/
1-object.js
File metadata and controls
47 lines (39 loc) · 775 Bytes
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
'use strict';
const asyncResult = () => ({
value: undefined,
onDone: null,
done(callback) {
this.onDone = callback;
return this;
},
resolve(value) {
this.value = value;
if (this.onDone) this.onDone(value);
return this;
}
});
// Usage
const persons = {
10: 'Marcus Aurelius',
11: 'Mao Zedong',
12: 'Rene Descartes',
};
const getPerson = (id) => {
const result = asyncResult();
setTimeout(() => {
result.resolve({ id, name: persons[id] });
}, 1000);
return result;
};
// Subscribe
const d1 = getPerson(10);
d1.done((value) => {
console.log('Resolved d1', value);
});
// Subscribe after resolve
const d2 = getPerson(11);
setTimeout(() => {
d2.done((value) => {
console.log('Resolved d2', value);
});
}, 1500);