Thunk函数

thunk函数实现generator函数的自动执行

const fs = require("fs");

const Thunk = function (fn) {
  return function (...args) {  //这是readFileThunk函数
    return function (callback) {
      return fn.call(this, ...args, callback);  // fs.readFile(...args, callback)
    };
  };
};

const readFileThunk = Thunk(fs.readFile); // 返回里面函数

function run(fn) {
  var gen = fn();
  function next(err, data) {
    /*
        开始执行yeild表达式--->readFileThunk的执行--> 返回最里层callback入参的函数
        result就是{value:function(callback){return fn.call(this, ...args, callback)},done:false}
        */
    var result = gen.next(data);
    if (result.done) return;
    /*
    next作为callback继续执行
    */
    result.value(next); 
  }
  next(); 
}

const g = function* () {
  const s1 = yield readFileThunk("./files/1.json");
  console.log(s1.toString());
  const s2 = yield readFileThunk("./files/2.json");
  console.log(s2.toString());
  const s3 = yield readFileThunk("./files/3.json");
  console.log(s3.toString());
};

run(g);

你可能感兴趣的:(Thunk函数)