class 实现一个Promise

const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
const PENDING = 'pending';

class MyPromise {
constructor(fn) {
    this.value = null;
    this.reason = null;
    this._status = PENDING;
    this.FULFILLED_CALLBACK_LIST = [];
    this.REJECTED_CALLBACK_LIST = [];
    try {
    fn(this.resolve.bind(this), this.reject.bind(this));
    } catch (error) {
    this.reject(error);
    }
}
get status() {
    return this._status;
}
set status(newStatus) {
    this._status = newStatus;
    switch (newStatus) {
    case FULFILLED: {
        this.FULFILLED_CALLBACK_LIST.forEach((callback) => {
        callback(this.value);
        });
        break;
    }
    case REJECTED: {
        this.REJECTED_CALLBACK_LIST.forEach((callback) => {
        callback(this.reason);
        });
        break;
    }
    }
}
resolve(value) {
    // 更新状态,更新 value
    if (this.status === PENDING) {
    this.value = value;
    this.status = FULFILLED;
    }
}
reject(reason) {
    // 更新状态,更新 reason
    if (this.status === PENDING) {
    this.reason = reason;
    this.status = REJECTED;
    }
}

then(onFulfilled, onRejected) {
    // 判断 onFulfilled, onRejected 是不是一个函数
    const realOnFulfilled = this.isFunction(onFulfilled)
    ? onFulfilled
    : (value) => value;
    const realOnRejected = this.isFunction(onRejected)
    ? onRejected
    : (reason) => reason;
    const promise2 = new MyPromise((resolve, reject) => {
    const fulfilledMicrotask = () => {
        try {
        const x = realOnFulfilled(this.value);
        resolve(x);
        } catch (error) {
        reject(error);
        }
    };

    const rejectedMicrotask = () => {
        try {
        const x = realOnRejected(this.reason);
        reject(x);
        } catch (error) {
        reject(error);
        }
    };

    switch (this.status) {
        case FULFILLED: {
        fulfilledMicrotask();
        break;
        }
        case REJECTED: {
        rejectedMicrotask();
        break;
        }
        case PENDING: {
        this.FULFILLED_CALLBACK_LIST.push(fulfilledMicrotask);
        this.REJECTED_CALLBACK_LIST.push(rejectedMicrotask);
        break;
        }
    }
    });
    return promise2;
}

isFunction(params) {
    return typeof params === 'function';
}
}
//   测试
const obj = {
name: 'zs',
};
const p = new MyPromise((resolve, reject) => {
console.log(1);
resolve(2);
})
.then(obj)
.then((res) => {
    console.log(res);
    console.log(1234);
});

猜你喜欢

转载自blog.csdn.net/m0_56274171/article/details/124105218
今日推荐