forked from HowProgrammingWorks/AsyncAwait
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9-thenable.js
More file actions
62 lines (49 loc) · 1.12 KB
/
9-thenable.js
File metadata and controls
62 lines (49 loc) · 1.12 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
55
56
57
58
59
60
61
62
'use strict';
const fs = require('fs');
class Thenable {
constructor() {
this.thenHandler = null;
this.next = null;
}
then(fn) {
this.fn = fn;
const next = new Thenable();
this.next = next;
return next;
}
async resolve(value) {
const fn = this.fn;
if (fn) {
const next = await fn(value);
if (this.next) {
this.next.resolve(next);
}
}
}
}
// Usage
const readFile = filename => {
const thenable = new Thenable();
fs.readFile(filename, 'utf8', (err, data) => {
if (err) throw err;
thenable.resolve(data);
});
return thenable;
};
const delay = fn => (...args) => {
const thenable = new Thenable();
setTimeout(thenable.resolve.bind(thenable), 1000, fn(...args));
return thenable;
};
const fn = val => val;
const mul = val => val * 5;
const add = val => val + 2;
const fnDel = delay(fn);
const mulDel = delay(mul);
const addDel = delay(add);
(async () => {
const file1 = await readFile('9-thenable.js');
console.dir({ length: file1.length });
const res = await fnDel(7).then(mulDel).then(add).then(addDel);
console.log(res);
})();