异步编程技巧
发布于 8 小时前 作者 gzhangzy 126 次浏览 来自 分享

先看一个例子

var Promise = require("promise-tiny");

new Promise(function(resolve, reject) {	// 注意resolve和reject这两个参数,实际就是then和catch的参数
        var r = Math.random();
        if(r >= 0.5) resolve('success');
        else reject('fail');
    })
   .then(function(value) {		// >=0.5时,调用这个函数
        console.log(value);
    })
   .catch(function(value) {		// <0.5时,调用这个函数
        console.log(value);
    });

promise-tiny的实现代码

class Promise {				// 这段代码主要用于揭示实现原理,对理解异步编程技巧很有帮助
    constructor(factory) {
        this.flag = 'Pending';		// flag值域 'Pending','Resolved','Reject'
        this.args = [];
        this.func = {};

        function next(flag, value) {	// next这个函数是精华,factory没有参数运行起来,全靠它了
            this.flag = flag;
            this.args = [].concat(value);
            this.func[flag] && this.func[flag].apply(undefined, this.args);
        }

        factory(next.bind(this, 'Resolved'), next.bind(this, 'Rejected'));
        return this;
    }

    then(func) {
        if(this.flag==='Resolved') func.apply(undefined, this.args);
        else this.func['Resolved'] = func;
        return this;
    }

    catch(func) {
        if(this.flag==='Rejected') func.apply(undefined, this.args);
        else this.func['Rejected'] = func;
        return this;
    }
}

理解了原理,就觉得应该能实现的更好。还是先看一个例子

var Steps = require("promise-tiny/Steps");

class Count {
    constructor() {
        this._step = 0;
    }
    get step() {
        return this._step;
    }
    set step(n) {
        this._step = n;
    }
}

new Steps(new Count)
   .on('Begin', function(next) {
        this.step++;
        next('check', 'Begin');
    })
   .on('check', function(next, ...args) {
        this.step++;
        next('create', [].concat(args, 'check'));
    })
   .on('create', function(next, ...args) {
        this.step++;
        next('error', [].concat(args, 'create'));
    })
   .on('logout', function(next, ...args) {
        this.step++;
        next('End', [].concat(args, 'logout'));
    })
   .on('error', function(next, ...args) {
        this.step++;
        next('End', [].concat(args, 'error'));
    })
   .on('End', function(next, ...args) {
        this.step++;
        console.log('Steps: '+this.step, 'trace: '+[].concat(args, 'End').join('->'));
    });

结果

Steps: 5 trace: Begin->check->create->error->End

[先写到这里]

回到顶部