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

先看一个例子

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','Rejected'
        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'));
    }

    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('->'));

        next('new Steps', { id: '!Count', count: 0 });
    })
   .on('Begin', function(next, ...args) {
        this.count++;
        next('info', [].concat(args, 'Begin'));
    })
   .on('info', function(next, ...args) {
        this.count++;
        next('logout', [].concat(args, 'info'));
    })
   .on('logout', function(next, ...args) {
        this.count++;
        next('End', [].concat(args, 'logout'));
    })
   .on('error', function(next, ...args) {
        this.count++;
        next('End', [].concat(args, 'error'));
    })
   .on('End', function(next, ...args) {
        this.count++;
        console.log('Count: '+this.count, 'trace: '+[].concat(args, 'End').join('->'), this.id);
    });

结果

Steps: 5 trace: Begin->check->create->error->End
Count: 4 trace: new Steps->Begin->info->logout->End !Count

Promise代码体会

带有一个函数参数的函数 f1(f2) ,可以先造一个f2’,这样就可以把它执行了 f1(f2’)。

这个f2’的功能要这样实现:当执行到f2’时,f2’要检查真实的f2是否已经准备好了?如果准备好了,就调用真实的f2;否则,要把调用f2的参数都记下来,等f2准备好时调用。

这样就不需要要求调用f1时,f2必须准备好了。但额外要提供一个提交f2的方法。

以上就是Promise揭示的异步编程技巧。在Promise中,factory是f1;resolve和reject是f2’;then和catch是提交f2的方法。

Promise揭示的编程技巧为什么能改善异步编程方法?

这主要是因为程序员编写程序时,总是按照自己的思考习惯和代码组织习惯编写程序,偏向于同步执行过程。代码的提交次序与机器执行次序有着很大差异!Promise揭示的技巧使程序员能够不用考虑机器的执行次序,给点代码就先执行着,碰到没给的代码就记录下来,等后续代码提交后接着执行。这样,程序员只要保证最终把所有代码都提交就可以了。

应该有更好的实现

既然有这样好的思路,再回头看看Promise的实现,其中缺陷不言而喻。Steps是一次尝试,考虑的问题要比Promise多一些。

1 回复

实现很精致,比大部分Promise的实现简洁。发现一个问题:三处apply需要异步调用。

回到顶部