zoukankan      html  css  js  c++  java
  • 简单模拟CO模块

    promise方式:

    // 对co模块的简单模拟
    
    function run(gen){
        var g = gen();
        function next(data){
            var result = g.next(data);
            if (result.done) return result.value;
            result.value.then(function(data){
                next(data);
            });
        }
        next();
    }
    
    function a(aa){
        return new Promise(function (resolve, reject){
            setTimeout(function (){
                console.log(aa);
                resolve('dataA');
            }, 1000);
        });
    }
    
    function b(bb){
        return new Promise(function (resolve, reject){
            setTimeout(function (){
                console.log(bb);
                resolve('dataB');
            }, 1000);
        });
    }
    
    function *gen(){
        console.log(yield a('aa'));
        console.log(yield b('bb'));
    }
    
    run(gen);
    
    /*
    等一秒
    aa
    dataA
    等一秒
    bb
    dataB
    */

    thunk方式:

    // 对co模块的简单模拟
    
    function run(fn) {
        var gen = fn();
        function next(err, data) {
            var result = gen.next(data);
            if (result.done) return;
            result.value(next);
        }
        next();
    }
    
    var Thunk = function(fn){
        return function(...args){
            return function(callback){
                return fn.call(this, ...args, callback);
            };
        };
    };
    
    function a(aa, cb){
        setTimeout(function (){
            console.log(aa);
            cb(null, 'dataA');
        }, 1000);
    }
    
    function b(bb, cb){
        setTimeout(function (){
            console.log(bb);
            cb(null, 'dataB');
        }, 1000);
    }
    
    var aThunk = Thunk(a);
    var bThunk = Thunk(b);
    
    function *gen(){
        console.log(yield aThunk('aa'));
        console.log(yield bThunk('bb'));
    }
    
    run(gen);
    
    /*
    等一秒
    aa
    dataA
    等一秒
    bb
    dataB
    */
  • 相关阅读:
    一.js高级(4)-函数调用-this指向-其他参数
    一.js高级(3)-原型及其继承
    一.js高级(2) -构造函数-原型对象
    curl ,post,get (原创)
    PDOHelper (原创)
    php 写日志函数(原创)
    一致性hash 算法 (转)
    md5 c# unicode 互换(原创)
    php auto_load mvc 接口框架(原创)
    php获取uniqid
  • 原文地址:https://www.cnblogs.com/jyuf/p/7857405.html
Copyright © 2011-2022 走看看