本章来自己开发一个Promise实现,提升异步编程的能力。
首先声明定义类并声明Promise状态与值,有以下几个细节需要注意。
executor为执行者
当执行者出现异常时触发拒绝状态
使用静态属性保存状态值
状态只能改变一次,所以在resolve与reject添加条件判断
因为 resolve或rejected方法在executor中调用,作用域也是executor作用域,这会造成this指向window,现在我们使用的是class定义,this为undefined。
class HD {
static PENDING = "pending";
static FULLFILLED = "fulfilled";
static REJECTED = "fullfilled";
constructor(executor){
this.status = HD.pending;
this.value = null;
this.callbacks = [];
try {
executor(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error);
}
}
resolve(value) {
if (this.status == HD.PENDING) {
this.status = HD.FULFILLED;
this.value = value;
setTimeout(() => {
this.callbacks.map(callback => {
callback.onFulfilled(value);
})
})
}
}
reject(value) {
if (this.status == HD.PENDING) {
this.status = HD.REJECTED;
this.value = value;
setTimeout(() => {
this.callbacks.map(callback => {
callback.onRejected(value);
})
})
}
}
then(onFulfilled, onRejected) {
if (typeof onFulfilled != "function") {
onFulfilled = value => value;
}
if (typeof onRejected != "function") {
onRejected = value => value;
}
return new HD((resolve, reject) => {
if (this.status == HD.PENDING) {
this.callbacks.push({
onFulfilled: value => {
try {
let result = onFulfilled(value);
if (result instanceof HD) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
},
onRejected: value => {
try {
let result = onRejected(value);
if (result instanceof HD) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
}
});
};
if (this.status == HD.FULFILLED) {
setTimeout(() => {
try {
let result = onFulfilled(this.value);
if (result instanceof HD) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
})
}
if (this.status == HD.REJECTED) {
setTimeout(() => {
try {
let result = onRejected(this.value);
if (result instanceof HD) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
})
}
})
}
static resolve(value) {
return new HD((resolve, reject) => {
if (value instanceof HD){
value.then(resolve, reject);
} else {
resolve(value);
}
})
}
static reject(reason) {
return new HD((null, reject) => {
reject(reason);
}
}
}
04-09
1万+
10-30
302
09-25
3545