手写题(前端)

24 阅读1分钟

实现一个promise

`const PENDING = "PENDING";

const FULFILLED = "FULFILLED";

const REJECTED = "REJECTED";

class MyPromise {

constructor(executor) {

this.status = PENDING; // 初始状态

this.value = undefined; // 成功的值

this.reason = undefined; // 失败的原因

this.onFulfilledCallbacks = []; // 成功回调队列

this.onRejectedCallbacks = []; // 失败回调队列

const resolve = (value) => {

if (this.status === PENDING) {

this.status = FULFILLED;

this.value = value;

this.onFulfilledCallbacks.forEach((fn) => fn());

}

};

const reject = (reason) => {

if (this.status === PENDING) {

this.status = REJECTED;

this.reason = reason;

this.onRejectedCallbacks.forEach((fn) => fn());

}

};

try {

executor(resolve, reject);

} catch (error) {

reject(error);

}

}

then(onFulfilled, onRejected) {

onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (v) => v;

onRejected =

typeof onRejected === "function"

? onRejected

: (err) => {

throw err;

};

const promise2 = new MyPromise((resolve, reject) => {

if (this.status === FULFILLED) {

setTimeout(() => {

try {

const x = onFulfilled(this.value);

resolve(x);

} catch (error) {

reject(error);

}

});

}

if (this.status === REJECTED) {

setTimeout(() => {

try {

const x = onRejected(this.reason);

resolve(x);

} catch (error) {

reject(error);

}

});

}

if (this.status === PENDING) {

this.onFulfilledCallbacks.push(() => {

setTimeout(() => {

try {

const x = onFulfilled(this.value);

resolve(x);

} catch (error) {

reject(error);

}

});

});

this.onRejectedCallbacks.push(() => {

setTimeout(() => {

try {

const x = onRejected(this.reason);

resolve(x);

} catch (error) {

reject(error);

}

});

});

}

});

return promise2;

}

}

// 测试代码

new MyPromise((resolve, reject) => {

setTimeout(() => resolve("成功"), 1000);

})

.then((res) => {

console.log(res); // 输出: 成功

return "下一步";

})

.then((res) => console.log(res)); // 输出: 下一步`