promise实现如下
- promise的实例状态唯一性 (pending、fulfilled、rejected)
- 实现promise有两个变量分别储存resolve、reject处理的值
- promise 提供resolve、reject 方法。这两个方法需要作为executor的参数提供给开发者使用
function Promise(executor) {
this.status = "pending";
this.value = "";
this.reason = "";
this.OnFunctionArrayFuill = [];
this.OnFunctionArrayError = [];
let self = this;
function resolve(value) {
setTimeout(() => {
if (self.status == "pending") {
self.value = value;
self.status = "fuilled";
self.OnFunctionArrayFuill.forEach((func) => {
func();
});
}
});
}
function reject(error) {
setTimeout(() => {
if (self.status == "pending") {
self.status = "rejected";
self.reason = error;
self.OnFunctionArrayError.forEach((errFunc) => {
errFunc();
});
}
});
}
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}