簡易promise對象

promise三種狀態: pending(進行中),resolve(成功),reject(失敗)promise

promise方法thenthis

function KingPromise(fn) {
    this.status = 'pending';
    this.fn = fn;
    this.result = null;
    this.error = null;
    this.eventQueue = [];
    fn(this.resolve.bind(this), this.reject.bind(this));
}


KingPromise.prototype.resolve = function (res) {
    this.status = 'resolve';
    this.result = res;
    for (var i = 0; i < this.eventQueue.length; i++) {
        this.eventQueue[i](this.result);
    }
}

KingPromise.prototype.reject = function (err) {
    this.error = err;
    this.status = 'reject';
    for (var i = 0; i < this.eventQueue.length; i++) {
        this.eventQueue[i](this.error);
    }
}

KingPromise.prototype.then = function (cb) {
    if (typeof cb !== 'function') {
        throw 'then方法參數不是function!';
        return this;
    }
    if (this.status == 'pending') {
        //push到事件隊列
        this.eventQueue.push(cb);
    } else if (this.status == 'resolve') {
        cb(this.result);
    } else if (this.status == 'reject') {
        cb(this.error);
    }
    return this;
}

Demo:prototype

let doSth = new KingPromise((resolve, reject) => {
    setTimeout(() => {
        console.log('KingPromise_resolve');
        resolve();
    }, 5000)
});

doSth.then(() => {
    console.log('1');
})
doSth.then(() => {
    console.log('2');
})
相關文章
相關標籤/搜索