const PENDING_STATE = "pending";
const FULLFILL_STATE = "fullfilled";
const REJECTED_STATE = "refected";
class Promise {
constructor(executor) {
if (typeof executor !== "function") {
throw new Error("Promise executor must be a function.");
}
this.__state = PENDING_STATE;
this.__chains = [];
const resolve = res => {
// 当且仅当状态是 pending 状态时才可以调用resolve或者reject,防止二次调用。
if (this.__state !== PENDING_STATE) return;
// resolve要处理promise,判断是否有then属性
if (res && typeof res.then === "function") {
return res.then();
}
this.__state = FULLFILL_STATE;
this.__internalValue = res;
for (const { onFullFilled } of this.__chains) {
onFullFilled(res);
}
};
const reject = err => {
if (this.__state !== PENDING_STATE) return;
this.__state = REJECTED_STATE;
this.__internalValue = err;
for (const { onRejected } of this.__chains) {
onRejected(err);
}
};
// 规范中,Promise初始化就调用executor
try {
executor(resolve, reject);
} catch (err) {
// 如果处理器函数抛出一个同步错误,我们认为这是一个失败状态
reject(err);
}
}
then(onFullFilled, onRejected) {
return new Promise((resolve, reject) => {
// 参考上述的constructor实现
const _onFullFilled = res => {
try {
resolve(onFullFilled(res));
} catch (err) {
reject(err);
}
};
const _onRejected = err => {
try {
reject(onRejected(res));
} catch (err) {
reject(err);
}
};
if (this.__state === FULLFILL_STATE) {
_onFullFilled(this.__internalValue);
} else if (this.__state === REJECTED_STATE) {
_onRejected(this.__internalValue);
} else {
this.__chains.push({
onFullFilled: _onFullFilled,
onRejected: _onRejected
});
}
});
}
}