function myPromise(exector){
const _this = this;
_this.status = "pending";
_this.value = undefined;
_this.callFn = {};
function resolve(value){
if(_this.status !== "pending")return;
_this.status = "resolved";
_this.value = value;
setTimeout(() => {
_this.callFn.onResolved && _this.callFn.onResolved(value);
});
}
function reject(reason){
if(_this.status !=="pending")return;
_this.status = "rejected";
_this.value = reason;
setTimeout(() => {
_this.callFn.onRejected && _this.callFn.onRejected(reason);
});
}
exector(resolve,reject);
}
myPromise.prototype.then = function(onResolved,onRejected){
const _this = this;
onRejected = typeof onRejected !=="function"?function(reason){
throw reason;
}:onRejected;
onResolved = typeof onResolved !=="function"?function(value){
return value;
}:onResolved;
return new myPromise((resolve,reject)=>{
_this.callFn.onResolved=function(value){
try{
const re = onResolved(value);
if (re instanceof myPromise){
re.then((data)=>{
resolve(data);
},(reason)=>{
reject(reason);
});
}else{
resolve(re);
}
}catch(e){
reject(e);
}
};
_this.callFn.onRejected=function(reason){
try{
const re = onRejected(reason);
if(re instanceof myPromise){
re.then((value)=>{
resolve(value);
})
}else{
resolve(re);
}
}catch(e){
reject(e);
}
};
})
}
myPromise.prototype.catch = function(onRejected){
return this.then(undefined,onRejected);
}
myPromise.prototype.finally = function(onResolved){
return this.then((value)=>{
const re = onResolved();
if(re instanceof myPromise){
return re.then(()=>{
return value;
})
}else{
return value;
}
},(reason)=>{
const re = onResolved();
if(re instanceof myPromise){
re.then(()=>{
throw reason;
})
}else{
throw reason;
}
})
}
myPromise.resolve = function(value){
return new myPromise((resolve,reject)=>{
if(value instanceof myPromise){
value.then((value)=>{
resolve(value);
},(reason)=>{
reject(reason);
})
}else{
resolve(value);
}
})
}
myPromise.reject = function(){
return new myPromise((resolve,reject)=>{
reject(reason);
})
}
myPromise.all=function(promises){
return new myPromise((resolve,reject)=>{
const promiseArr= [];
const promiseL = promises.length;
let promsieCount = 0;
promises.forEach((promise,index)=>{
promise.then((value)=>{
promsieCount++;
promiseArr[index]=value;
if(promsieCount===promiseL){
resolve(promiseArr);
}
},(reason)=>{
reject(reason)
})
})
})
}
myPromise.allSettled = function (promises){
return new myPromise((resolve,reject)=>{
const promisel =promises.length;
let promiseCount = 0;
const promiseArr =[];
promises.forEach((promise,index)=>{
promise.then((value)=>{
promiseCount++;
promiseArr[index]={
status:"resolved",
value
};
if(promiseCount === promisel){
resolve(promiseArr);
}
},(reason)=>{
promiseCount++
promiseArr[index]={
status:"rejected",
reason
}
if(promiseCount === promisel){
resolve(promiseArr);
}
})
})
})
}