Thunk 函数:
const Thunk = function(fn) {
return function (...args) {
return function (callback) {
return fn.call(this, ...args, callback);
}
};
};
生成 fs.readFile 的 Thunk 函数:
var readFileThunk = Thunk(fs.readFile);
readFileThunk(fileA)(callback);
基于 Thunk 函数的 Generator 执行器:
function run(fn) {
var gen = fn();
function next(err, data) {
var result = gen.next(data);
if (result.done) return;
result.value(next);
}
next();
}
function* g() {
// ...
}
run(g);
例子:
var g = function* (){
var f1 = yield readFileThunk('fileA');
var f2 = yield readFileThunk('fileB');
// ...
var fn = yield readFileThunk('fileN');
};
run(g);