实现Promise主要几步:
- Promise的基本结构
- new一个实例,实例中传入参数,自动执行
- 三种状态的实现
- then的实现
- 异步的实现
- then的链式调用
class Commitment {
static PENDING = '待定';
static FULFILLED = '成功';
static REJECT = '拒绝';
constructor(func) {
this.result = null;
this.status = Commitment.PENDING;
this.resolveCallbacks = [];
this.rejectCallbacks = [];
try {
func(this.resolve.bind(this), this.reject.bind(this));
} catch {
this.reject(error);
}
}
resolve(result) {
setTimeout(() => {
if (this.status === Commitment.PENDING) {
this.status = Commitment.FULFILLED;
this.result = result;
this.resolveCallbacks.forEach(callback => {
callback(result);
})
}
})
}
reject(result) {
setTimeout(() => {
if (this.status === Commitment.PENDING) {
this.status = Commitment.REJECT;
this.result = result;
this.rejectCallbacks.forEach(callback => {
callback(result)
})
}
})
}
then(onFULFILLED, onREJECTED) {
return new Commitment((resolve, reject) => {
if (this.status === Commitment.PENDING) {
this.resolveCallbacks.push(onFULFILLED);
this.rejectCallbacks.push(onREJECTED);
}
if (this.status === Commitment.FULFILLED) {
setTimeout(() => {
onFULFILLED(this.status);
})
}
if (this.status === Commitment.REJECT) {
setTimeout(() => {
onREJECTED(this.status)
})
}
})
}
}