Promise 三个状态
- pending
- fulfilled
- rejected
executor 同步执行器,并为执行器定义需要的 resolve、reject
利用 try…catch ,catch 调用 reject
利用发布订阅设计模式解决异步代码的执行
- this.onResolvedCallback = []; this.onRejectedCallback = [];
- 在 then 方法中订阅
resolve,reject 发布
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onResolvedCallback = [];
this.onRejectedCallback = [];
const resolve = (value) => {
this.state = 'fulfilled';
this.value = value;
this.onResolvedCallback.forEach((fn) => fn());
},
reject = (reason) => {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallback.forEach((fn) => fn());
};
try {
executor(resolve, reject);
} catch (reason) {
reject(reason);
}
}
then(onFulfilled, onRejected) {
let x;
return new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
try {
x = onFulfilled(this.value);
resolve();
} catch (e) {
reject(e);
}
}
if (this.state === 'rejected') {
try {
x = onRejected(this.reason);
resolve(x);
} catch (e) {
reject(e);
}
}
if (this.state === 'pending') {
this.onResolvedCallback.push(() => {
try {
x = onFulfilled(this.value);
resolve(x);
} catch (e) {
reject(e);
}
});
this.onRejectedCallback.push(() => {
try {
x = onRejected(this.reason);
resolve(x);
} catch (e) {
reject(e);
}
});
}
});
}
}