-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path9-recursive.js
More file actions
54 lines (47 loc) · 1.1 KB
/
9-recursive.js
File metadata and controls
54 lines (47 loc) · 1.1 KB
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
'use strict';
const fs = require('node:fs');
class Thenable {
next = null;
then(onSuccess) {
this.onSuccess = onSuccess;
this.next = new Thenable();
return this.next;
}
resolve(value) {
if (!this.onSuccess) return;
const next = this.onSuccess(value);
if (!next) return;
if (!next.then) return void this.next.resolve(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('1-contract.js')
.then((data) => {
console.dir({ file1: data.length });
return readFile('2-usage.js');
})
.then((data) => {
console.dir({ file2: data.length });
return readFile('3-class.js');
})
.then((data) => {
console.dir({ file3: data.length });
return 'I will be printed by callback in the next then';
})
.then((data) => {
console.dir({ text: data });
})
.then(() => {
console.log('Will be never printed');
});