zoukankan      html  css  js  c++  java
  • Promise 实现,因为无法模拟微任务, 干错没用异步

    function Then(fn){
        var __self__ = this;
        this.node = null;
        this.err = null;
        this.catchFn = null;
        this.endFn = null;
        this.running = true;
        this.queue = [];
        fn(function(value){
            __self__._res(value);
        }, function(value){
            __self__._rej(value);
        });
    }
    Then.prototype._next = function(){
        var __self__ = this;
        var callback = arguments.callee;
        if(this.queue.length == 0){
            this.running = false;
            this.endFn && this.endFn.call(this, this.node);
            return;
        }
        var node;
        this.running = true;
        if(this.node.constructor === Then){
            this.node.end(function(value){
                node = value;
                __self__.node = node;
                __self__.running = false;
                if(__self__.queue.length > 0){
                    callback.call(__self__);
                }
            })
        }else{
            var fn = this.queue.shift();
            node = fn(this.node);
            this.node = node;
            this.running = false;
            if(this.queue.length > 0){
                callback.call(this);
            }
        }
    }
    Then.prototype._res = function(value){
        this.node = value;
        this._next();
        return this;
    }
    Then.prototype._rej = function(value){
        this.err = value;
        return this;
    }
    Then.prototype.then = function(fn){
        this.queue.push(fn);
        if(!this.running){
            this._next();
        }
        return this;
    }
    Then.prototype.end = function(fn){
        this.endFn = fn;
        this._next();
        return this;
    }
    Then.prototype.catch = function(value){
    }
    
    new Then(function(res, rej){
        setTimeout(function(){
        console.log(1);
            res(true)
        },1000)
    }).then(function(){
        return new Then(function(res, rej){
            res('2');
        }).then(function(data){
            return '3';
        });
    }).then(function(data){
        console.log(4);
        console.log(data);
        return '3';
    });
  • 相关阅读:
    Visio 2003 怎样将用例图画的更美观些
    Mvc项目实例 MvcMusicStore 四
    Mvc项目实例 MvcMusicStore 三
    Lock 会引起死锁吗
    进程和线程
    vb.net winform pos机并口打印机打印以及开钱箱。。。。
    .net winfrom 定义全局快捷键!
    WebBrowser中HTML的js与winform中其他的窗体调用。。。
    [转]确认网络环境3G/WIFI
    图片分割的代码
  • 原文地址:https://www.cnblogs.com/jiajiaobj/p/13654854.html
Copyright © 2011-2022 走看看