-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path6-promise.js
More file actions
56 lines (45 loc) · 937 Bytes
/
6-promise.js
File metadata and controls
56 lines (45 loc) · 937 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
48
49
50
51
52
53
54
55
56
'use strict';
class Future {
#executor;
constructor(executor) {
this.#executor = executor;
}
static of(value) {
return new Future((resolve) => resolve(value));
}
chain(fn) {
return new Future((resolve, reject) =>
this.fork(
(value) => fn(value).fork(resolve, reject),
(error) => reject(error),
),
);
}
map(fn) {
return this.chain((value) => Future.of(fn(value)));
}
fork(successed, failed) {
this.#executor(successed, failed);
}
promise() {
return new Promise((resolve, reject) => {
this.fork(
(value) => resolve(value),
(error) => reject(error),
);
});
}
}
// Usage
const main = async () => {
const value = await Future.of(6)
.map((x) => {
console.log('future1 started');
return x;
})
.map((x) => ++x)
.map((x) => x ** 3)
.promise();
console.log('result', value);
};
main();