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

 

posted @ 2020-09-11 22:40  潴哥  阅读(212)  评论(0编辑  收藏  举报