Skip to content

Commit 2b6d369

Browse files
committed
Basic ideas
1 parent 73c937b commit 2b6d369

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

JavaScript/1-object.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
3+
const asyncResult = () => ({
4+
value: undefined,
5+
onDone: null,
6+
done(callback) {
7+
this.onDone = callback;
8+
return this;
9+
},
10+
resolve(value) {
11+
this.value = value;
12+
if (this.onDone) this.onDone(value);
13+
return this;
14+
}
15+
});
16+
17+
// Usage
18+
19+
const persons = {
20+
10: 'Marcus Aurelius',
21+
11: 'Mao Zedong',
22+
12: 'Rene Descartes',
23+
};
24+
25+
const getPerson = id => {
26+
const result = asyncResult();
27+
setTimeout(() => {
28+
result.resolve({ id, name: persons[id] });
29+
}, 1000);
30+
return result;
31+
};
32+
33+
// Subscribe
34+
const d1 = getPerson(10);
35+
d1.done(value => {
36+
console.log('Resolved d1', value);
37+
});
38+
39+
// Subscribe after resolve
40+
const d2 = getPerson(11);
41+
setTimeout(() => {
42+
d2.done(value => {
43+
console.log('Resolved d2', value);
44+
});
45+
}, 1500);

JavaScript/2-after.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'use strict';
2+
3+
const asyncResult = () => ({
4+
value: undefined,
5+
onDone: null,
6+
resolved: false,
7+
done(callback) {
8+
this.onDone = callback;
9+
if (this.resolved) callback(this.value);
10+
return this;
11+
},
12+
resolve(value) {
13+
this.value = value;
14+
this.resolved = true;
15+
if (this.onDone) this.onDone(value);
16+
return this;
17+
}
18+
});
19+
20+
// Usage
21+
22+
const persons = {
23+
10: 'Marcus Aurelius',
24+
11: 'Mao Zedong',
25+
12: 'Rene Descartes',
26+
};
27+
28+
const getPerson = id => {
29+
const result = asyncResult();
30+
setTimeout(() => {
31+
result.resolve({ id, name: persons[id] });
32+
}, 1000);
33+
return result;
34+
};
35+
36+
// Subscribe
37+
const d1 = getPerson(10);
38+
d1.done(value => {
39+
console.log('Resolved d1', value);
40+
});
41+
42+
// Subscribe after resolve
43+
const d2 = getPerson(11);
44+
setTimeout(() => {
45+
d2.done(value => {
46+
console.log('Resolved d2', value);
47+
});
48+
}, 1500);

0 commit comments

Comments
 (0)