-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path4-class.js
More file actions
48 lines (40 loc) · 803 Bytes
/
4-class.js
File metadata and controls
48 lines (40 loc) · 803 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
'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);
}
}
// Usage
Future.of(6)
.map((x) => {
console.log('future1 started');
return x;
})
.map((x) => ++x)
.map((x) => x ** 3)
.fork(
(value) => {
console.log('future result', value);
},
(error) => {
console.log('future failed', error.message);
},
);