生成器自动运行

Posted by 鑫鑫 Blog on June 14, 2019

layout: post title: JavaScript ajax的 readyState状态 subtitle: JavaScript生成器如何自动运行 date: 2019-6-14 author: xinxin header-img: img/tag-bg-o.jpg catalog: true tags: - JavaScript - es6 —

var fs = require('fs');
var thunkify = require('thunkify');
var readFileThunk = thunkify(fs.readFile);
function run(fn) {
    var gen = fn();
    function next(err, data) {
        var result = gen.next(data);
        if (result.done) return;
        result.value(next);//value这传递回调函数
    }

    next();
}
var g = function* (){
    var f1 = yield readFileThunk('1.txt');
    var f2 = yield readFileThunk('2.txt');
    // ...
    var fn = yield readFileThunk('3.txt');
};
run(g)
// 正常版本的readFile(多参数版本)
fs.readFile(fileName, callback);

// Thunk版本的readFile(单参数版本)
var Thunk = function (fileName) {
  return function (callback) {
    return fs.readFile(fileName, callback);
  };
};

var readFileThunk = Thunk(fileName);
readFileThunk(callback);
var Thunk = function(fn){
  return function (){
    var args = Array.prototype.slice.call(arguments);
    return function (callback){
      args.push(callback);
      return fn.apply(this, args);
    }
  };
};

// ES6版本
const Thunk = function(fn) {
  return function (...args) {
    return function (callback) {
      return fn.call(this, ...args, callback);
    }
  };
};

thunkify源码

function thunkify(fn) {
  return function() {
    var args = new Array(arguments.length);
    var ctx = this;

    for (var i = 0; i < args.length; ++i) {
      args[i] = arguments[i];
    }

    return function (done) {
      var called;

      args.push(function () {
        if (called) return;
        called = true;
        done.apply(null, arguments);
      });

      try {
        fn.apply(ctx, args);
      } catch (err) {
        done(err);
      }
    }
  }
};
var readFileThunk = Thunk(fs.readFile);
readFileThunk(fileA)(callback);