Skip to content

Commit ce92864

Browse files
committed
Implement simple Thenable
1 parent 0a5b1d8 commit ce92864

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

JavaScript/a-thenable.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
5+
class Thenable {
6+
7+
constructor() {
8+
this.thenHandler = null;
9+
this.next = null;
10+
}
11+
12+
then(fn) {
13+
this.fn = fn;
14+
const next = new Thenable();
15+
this.next = next;
16+
return next;
17+
}
18+
19+
resolve(value) {
20+
const fn = this.fn;
21+
if (fn) {
22+
const next = fn(value);
23+
if (next) {
24+
next.then(value => {
25+
this.next.resolve(value);
26+
});
27+
}
28+
}
29+
}
30+
31+
}
32+
33+
// Usage
34+
35+
const readFile = filename => {
36+
const thenable = new Thenable();
37+
fs.readFile(filename, 'utf8', (err, data) => {
38+
if (err) throw err;
39+
thenable.resolve(data);
40+
});
41+
return thenable;
42+
};
43+
44+
readFile('file1.txt')
45+
.then(data => {
46+
console.dir({ file1: data });
47+
return readFile('file2.txt');
48+
})
49+
.then(data => {
50+
console.dir({ file2: data });
51+
return readFile('file3.txt');
52+
})
53+
.then(data => {
54+
console.dir({ file3: data });
55+
});

0 commit comments

Comments
 (0)