手写promise函数

手写一个promise函数:

function Promise(executor) {
    var self = this;
    this.status = 'pending';
    this.value = undefined;
    this.reason = undefined;
    this.onResolvedCallbacks = [];
    this.onRejectedCallbacks = [];

    function resolve(value) {
        if(self.status === 'pending') {
            self.status = 'resolve';
            self.value = value;
            self.onResolvedCallbacks.forEach(function (fn) {
                fn();
            })
        }
    }
    function reject(reason) {
        if(self.status === 'pending') {
            self.status = 'rejected';
            self.reason = reason;
            self.onRejectedCallbacks.forEach(function (fn) {
                fn();
            })
        }
    }
    executor(resolve, reject);
}

Promise.prototype.then = function (infulfilled, inrejected) {
    var self = this;
    if(this.status === 'resolve') {
        infulfilled(this.value)
    }
    if(this.status === 'rejected') {
        inrejected(this.reason)
    }
    if(this.status === 'pending') {
        this.onResolvedCallbacks.push(function () {
            infulfilled(self.value)
        });
        this.onRejectedCallbacks.push(function () {
            inrejected(self.reason)
        });
    }
};

var p = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve('resolve');
    })
});

p.then(function (data) {
    console.log(data);
}, function (err) {
    console.log(err);
});

你可能感兴趣的:(JS)