Yang03 / blog

0 stars 0 forks source link

thunk #7

Open Yang03 opened 8 years ago

Yang03 commented 8 years ago

thunk

thunk 是‘传名调用’的一种策略.

        fs.readFile(fileName, callback);
        //thunk
        function thunk(fileName) {
            return function(callabck) {
                fs.readFile(fileName, callback) 
            }
        }
        var rs = thunk('xx');
        rs(function(){

        });

看看tj大神的thunkify

    /*  
        example
        function sum(x, y, callback) {
            var sum = x + y;
            callback.call(this, null, sum)
        }    
        var thunkSum = thunkify(sum); 
        // thunkSum = function () {}
        var sumFunc = thunkSum(1, 2);
        // sumFunc = function (){
        //   agrs = [
        //   1, 2, callback =  function(){ 
        //   if (called) return;
        //        called = true;
        //        done.apply(null, arguments);}
        //    ]
        // }
        sumFunc(function(err, data){
            console.log(data)
        })
        // sum(args)
    */
    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);
              }
            }
        }
      }  
Yang03 commented 6 years ago
const gen = function() * {
    const f1 = yield readFile('fileA');
    const f2 = yield readFile('fileB');
}

function run(fn) {
     const ge = fn()
     function next() {
         const result = ge.next(data)
         if(result.done) return
         result.value(next)
   }
   next()
}