const STATUS = {
PENDING: "PENDING",
FUFILLED: "FUFILLED",
REJECTED: "FUFILLED",
};
class Promise {
constructor(executor) {
this.status = STATUS.PENDING;
this.value = undefined;
this.reason = undefined;
const resolve = (val) => {
if (this.status == STATUS.PENDING) {
this.status = STATUS.PENDING;
this.value = val;
}
};
const reject = (reason) => {
if (this.status == STATUS.PENDING) {
this.status = STATUS.REJECTED;
this.reason = reason;
}
};
try {
executor(resolve, reject);
} catch (e) {
// 出错了走失败的逻辑
reject(e);
}
}
then(onFulFilled, onRejected) {
if (this.status == STATUS.FUFILLED) {
onFulFilled(this.value);
}
if ((this.status = STATUS.REJECTED)) {
onRejected(this.reason);
}
}
}
module.exports = Promise;