Promise 实现原理

function myPromise(exe) {
    let self = this;
    self.status = 'pending';
    self.value = null;
    self.reason = null;
    self.onResolveCbk = [];
    self.onRejectCbk = [];
    function resolve(value) {
        if (self.status === 'pending') {
            self.value = value;
            self.status = 'resolved';
            self.onResolveCbk.map(fn => fn());
        }
    }
    function reject(reason) {
        if (self.status === 'pending') {
            self.reason = reason;
            self.status = 'rejected';
            self.onResolveCbk.map(fn => fn());
        }
    }
    exe(resolve, reject);
}

myPromise.prototype.then = function(onFulfilled, onRejected) {
    let self = this;
    if (self.status === 'pending') {
        self.onResolveCbk.push(() => onFulfilled(self.value));
        self.onRejectCbk.push(() => onRejected(self.reason));
    }
    if (self.status === 'resolved') {
        onFulfilled(self.value);
    }
    if (self.status === 'rejected') {
        onRejected(self.reason);
    }
}

let mp = new myPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(2);
    }, 200);
});

mp.then(res => console.log('success', res));

Last updated