
- then 方法最多接受两个参数:用于
Promise 兑现和拒绝情况的回调函数。
- then 方法参数不是function类型的处理
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class FXPromise {
state = PENDING;
result = undefined;
constructor(fn) {
const resolveFunc = (res) => {
if (this.state === PENDING) {
this.result = res;
this.state = FULFILLED;
console.log("resolve ", res);
}
};
const rejectFunc = (res) => {
if (this.state === PENDING) {
this.result = res;
this.state = REJECTED;
console.log("reject ", res);
}
};
fn(resolveFunc, rejectFunc);
}
then(onFulfilled, onRejected) {
onFulfilled =
typeof onFulfilled === "function" ? onFulfilled : (x) => x;
onRejected =
typeof onRejected === "function"
? onRejected
: (x) => {
throw x;
};
if (this.state === FULFILLED) {
onFulfilled(this.result);
} else if (this.state === REJECTED) {
onRejected(this.result);
} else if (this.state === PENDING) {
}
}
}
new FXPromise((resolve, reject) => {
reject(222);
resolve(111);
}).then(
(res) => {
console.log("then res ", res);
},
(err) => {
console.log("then err ", err);
}
);
