首页 > 技术文章 > 简易promise对象

king2016 2017-03-21 12:52 原文

promise三种状态: pending(进行中),resolve(成功),reject(失败)

promise方法then

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:

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

doSth.then(() => {
    console.log('1');
})
doSth.then(() => {
    console.log('2');
})

推荐阅读