原文链接: js Thunk 函数
上一篇: ubuntu 安装 oh my zsh
参考
https://www.ruanyifeng.com/blog/2015/05/thunk.html
在 JavaScript 语言中,Thunk 函数替换的不是表达式,而是多参数函数,将其替换成单参数的版本,且只接受回调函数作为参数。
使用传统回调的方式和thunk包装的方式读取文件内容
const fs = require("fs");
const fileName = "t.txt";
// 正常版本的readFile(多参数版本)
fs.readFile(fileName, (err, data) => {
console.log("cb:", err, data.toString());
});
const Thunk = (fileName) => {
return (callback) => {
return fs.readFile(fileName, callback);
};
};
// Thunk版本的readFile(单参数版本)
const readFileThunk = Thunk(fileName);
readFileThunk((err, data) => {
console.log("thunk:", err, data.toString());
});
配合生成器读取文件
const fs = require("fs");
const thunkify = require("thunkify");
const txtPath = "./t.txt";
const jsPath = "./t2.txt";
const readFile = thunkify(fs.readFile);
const gen = function* () {
const r1 = yield readFile(txtPath);
console.log(r1.toString());
const r2 = yield readFile(jsPath);
console.log(r2.toString());
};
const g = gen();
const r1 = g.next();
r1.value(function(err, data){
if (err) throw err;
const r2 = g.next(data);
r2.value(function(err, data){
if (err) throw err;
g.next(data);
});
});
使用递归自动执行生成器函数, 前提是每一个异步操作,都要是 Thunk 函数,也就是说,跟在 yield 命令后面的必须是 Thunk 函数。
const fs = require("fs");
const thunify = require("thunkify");
const readFile = thunify(fs.readFile);
function run(fn) {
const gen = fn();
function next(err, data) {
const result = gen.next(data);
if (result.done || err) return;
result.value(next);
}
next();
}
const gen = function* () {
const f1 = yield readFile("./t.txt");
const f2 = yield readFile("./t2.txt");
console.log("f1:", f1.toString());
console.log("f2:", f2.toString());
};
run(gen);