内置属性status的流转:初始化(resolve、reject)、then、catch。并记录value和reason
class MyPromise {
constructor(executor) {
this.value = undefined;
this.reason = undefined;
this.status = 'pending';
const resolve = (value) => {
if (this.status === 'pending') {
this.value = value;
this.status = 'resolved';
}
};
const reject = (reason) => {
if (this.status === 'pending') {
this.reason = reason;
this.status = 'rejected';
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.status === 'resolved') {
onFulfilled(this.value);
} else if (this.status === 'rejected') {
onRejected(this.reason);
}
}
catch(onRejected) {
if (this.status === 'rejected') {
onRejected(this.reason);
}
}
}
© 版权声明
文章版权归作者所有,未经允许请勿转载,侵权请联系 admin@trc20.tw 删除。
THE END