-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththunk.js
54 lines (51 loc) · 1.24 KB
/
thunk.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
53
54
const path = require("path");
const fs = require("fs");
const { slice } = Array.prototype;
/**
*
* @param {*} fn
*/
const Thunkify = function(fn) {
return function() {
const args = Reflect.apply(slice, arguments, []);
const ctx = this;
return function(callback) {
let called;
if(!called) {
args.push(function() {
called = true;
callback.apply(null, arguments);
})
};
try {
fn.apply(ctx, args);
} catch(e) {
callback(e);
}
}
}
};
const readFileThunk = Thunkify(fs.readFile);
const gen = function* () {
let r1 = yield readFileThunk(path.join(__dirname, "1.txt"));
console.log(r1.toString());
let r2 = yield readFileThunk(path.join(__dirname, "2.txt"));
console.log(r2.toString());
};
function runGen(gen) {
const iter = gen();
function next(err, data) {
if(err) {
return;
}
const result = iter.next(data);
if(result.done) {
return result.value;
};
result.value((err, data) => {
next(err, data);
});
};
next();
};
runGen(gen)