class HD {
static PENDING ="pending";
static FUFILLED = "fulfilled";
static RESJECT = "rejected";
constructor(executor){
this.status = HD.PENDING;
this.value = null;
this.callbacks =[];
//如果在executor的执行过程中出现错误,那么可以通过try-catch
//来捕获错误并直接把错误传给reject方法
try{
//class默认情况下执行的是严格模式,this指向的是函数执行的上下文,为了让函数绑定class,所以用来bind
executor(this.resolve.bind(this),this.reject.bind(this));
}catch(error){
this.reject(error);
}
}
resolve(value){
/**promise的状态只能从pending转换成fulfilled或者rejected,
一旦改变状态就是不可逆的,也不存在从fulfilled-》rejected*/
if(this.status === HD.PENDING){
this.status = HD.FUFILLED;
this.value=value;
//当异步状态返回时,执行已经保存then方法入参的函数--成功
//setTimeout通过定时器,让then的回调异步执行
setTimeout(()=>{
this.callbacks.map((item)=>{
item.onFulfilled(value);
})
})
}
}
reject(value){
if(this.status === HD.PENDING){
this.status = HD.RESJECT;
this.value=value;
//当异步状态返回时,执行已经保存then方法入参的函数--失败
//setTimeout通过定时器,让then的回调异步执行
setTimeout(()=>{
console.log("this.callbacks",this.callbacks);
this.callbacks.map((item)=>{
item.onFulfilled(value);
})
})
}
}
then(onFulfilled,onRejected){
if(typeof onFulfilled !== "function"){
onFulfilled = ()=>{}
}
if(typeof onRejected !== "function"){
onRejected = ()=>{}
}
//then函数的每次执行都会返回一个新的HD对象以保证then能进行链式调用
let promise = new HD((resolve,reject)=>{
// 处理异步状态
if(this.status === HD.PENDING){
this.callbacks.push({onFulfilled:(value)=>{
this.parse(promise,onFulfilled(value),resolve,reject);
},onRejected:(value)=>{
this.parse(promise,onRejected(value),resolve,reject);
}});
}
//要执行then中的成功的方法,需要判断当前的状态是成功的才执行onFulfilled
if(this.status === HD.FUFILLED){
setTimeout(()=>{
this.parse(promise,onFulfilled(this.value),resolve,reject)
})
}
//要执行then中的失败的方法,需要判断当前的状态是成功的才执行onRejected
if(this.status === HD.RESJECT){
setTimeout(()=>{
this.parse(promise,onRejected(this.value),resolve,reject)
})
}
})
return promise;
}
//抽离代码公共部分
parse(promise,result,resolve,reject){
//不能在当前的promise处理中,再返回当前的promise
if(promise === result){
throw new TypeError("Chaining cycle detected");
}
try{
// then方法返回的promise的状态默认是-成功的,除非执行的代码出现错误才会返回失败
//当then的成功函数返回的是HD时,则需要手动调用一下HD的then方法,使得状态数据成功的传递下去给下一个then
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(value){
return new HD((resolve,reject)=>{
reject(value);
})
}
static all(promises){
return new HD((resolve,reject)=>{
let values =[];
promises.forEach(promise => {
promise.then((value)=>{
values.push(value);
if(values.length === promises.length){
resolve(values);
}
},(reason)=>{
reject(reason);
})
});
})
}
static race(promises){
return new HD((resolve,reject)=>{
promises.forEach(promise => {
promise.then((value)=>{
resolve(value);
},(reason)=>{
reject(reason);
})
});
})
}
}