-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathb-thenable.js
52 lines (45 loc) · 898 Bytes
/
b-thenable.js
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
'use strict';
const fs = require('node:fs');
class Thenable {
constructor() {
this.next = null;
}
then(fn) {
this.fn = fn;
const next = new Thenable();
this.next = next;
return next;
}
resolve(value) {
const fn = this.fn;
if (fn) {
const next = fn(value);
if (next) {
next.then((value) => {
this.next.resolve(value);
});
}
}
}
}
// Usage
const readFile = (filename) => {
const thenable = new Thenable();
fs.readFile(filename, 'utf8', (err, data) => {
if (err) throw err;
thenable.resolve(data);
});
return thenable;
};
readFile('file1.txt')
.then((data) => {
console.dir({ file1: data });
return readFile('file2.txt');
})
.then((data) => {
console.dir({ file2: data });
return readFile('file3.txt');
})
.then((data) => {
console.dir({ file3: data });
});