-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path8-futurify.js
More file actions
51 lines (40 loc) · 958 Bytes
/
8-futurify.js
File metadata and controls
51 lines (40 loc) · 958 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
'use strict';
const fs = require('node:fs');
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);
}
}
const futurify =
(fn) =>
(...args) =>
new Future((resolve, reject) => {
fn(...args, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
// Usage
const readFile = (name, callback) => fs.readFile(name, 'utf8', callback);
const futureFile = futurify(readFile);
futureFile('8-futurify.js')
.map((x) => x.length)
.fork((x) => console.log('File size:', x));