js Thunk 函数

原文链接: js Thunk 函数

上一篇: ubuntu 安装 oh my zsh

下一篇: webpack 插件 转换图片格式为webp

参考

https://www.ruanyifeng.com/blog/2015/05/thunk.html

在 JavaScript 语言中,Thunk 函数替换的不是表达式,而是多参数函数,将其替换成单参数的版本,且只接受回调函数作为参数。

使用传统回调的方式和thunk包装的方式读取文件内容

up-2daad3913a4fe7813e98848649e00bbbdfe.png

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());
});

配合生成器读取文件

up-52e4a5de2c497143c9d459e4b2d45e98eaf.png

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 函数。

up-9f6ae28deb448123d86cd672806eace15fa.png

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值