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';
    });
  • 相关阅读:
    小技巧
    常用的交互设计软件
    Android studio 使用SVN需要忽略的文件
    android studio 使用SVN 锁定文件,防止别人修改(基于Android studio 1.4 )
    git 和 github 关系?
    Double 数据保留两位小数一:五舍六入
    设计模式
    Java中关于日期类那些方法
    ios 开源免费接口
    华为招聘机试整理5:简单四则运算
  • 原文地址:https://www.cnblogs.com/jiajiaobj/p/13654854.html
Copyright © 2011-2022 走看看