class Promise{
construction(executor){
this.status = "pending";
this.resolveList = [];
this.rejectList = [];
const resolve = (args)=>{
if(this.status !== "pending"){
return
}
this.status = "fulfilled";
while(this.resolveList.length){
const callback = this.resolveList.shift();
callback(args)
}
}
const reject = (args) => {
if(this.status !== "pending"){
return
}
this.status = "rejected"
while(this.resolveList.length){
const callback = this.resolveList.shift();
callback(args)
}
}
executor(resolve,reject);
}
then(resolveCallback,rejectCallback){
this.resolveList.push(resolveCallback);
this.rejectList.push(rejectCallback);
}
// all promiseList列表中有一个失败 结果就为reject
all(promiseList){
const result = [];
return new Promise((resolve,reject)=>{
promiseList.map((item,i)=>{
// Promise.resolve()用于处理传入值不为Promise的情况
Promise.resolve(item).then((res)=>{
result[i] = res;
if(result.length === promiseList.length){
resolve(result)
}
},(err)=>{
reject(err)
})
})
})
}
race(promiseList){
return new Promise((resolve,reject)=>{
promiseList.map((item,i)=>{
// Promise.resolve()用于处理传入值不为Promise的情况
Promise.resolve(item).then((res)=>{
resolve(res)
},(err)=>{
reject(err)
})
})
})
}
}
网友评论