首先Promise有三个状态 PENDING、FULFILLED、REJECTED ,只能由PENDING改变为FULFILLED、REJECTED,并且只能改变一次
Promise接收一个函数,这个函数有两个参数resolve方法和reject方法
resolve将PENDING改变为FULFILLED
reject将PENDING改变为FULFILLED
这里还实现了then,all,rece方法
class MyPromise{
static PENDING = '待定';
static FULFILLED = '成功';
static REJECTED = '失败';
constructor(func){
this.status = MyPromise.PENDING;
this.result = null;
this.resolveCallback = [];
this.rejectCallback = [];
try {
func(this.resolve.bind(this),this.reject.bind(this));
} catch (error) {
this.reject(error)
}
}
resolve(result){
setTimeout(() => {
if(this.status == MyPromise.PENDING){
this.status = MyPromise.FULFILLED;
this.result = result;
this.resolveCallback.forEach(callback =>{
callback(result)
})
}
});
}
reject(result){
setTimeout(() => {
if(this.status == MyPromise.PENDING){
this.status = MyPromise.REJECTED;
this.result = result;
this.rejectCallback.forEach(callback =>{
callback(result)
})
}
});
}
then(onFULFILLED,onREJECTED){
return new MyPromise( (resolve,reject)=>{
onFULFILLED = typeof onFULFILLED === 'function'?onFULFILLED:()=>{}
onREJECTED = typeof onREJECTED === 'function'?onREJECTED:()=>{}
if(this.status == MyPromise.PENDING){
this.resolveCallback.push(onFULFILLED)
this.rejectCallback.push(onREJECTED)
}
if(this.status == MyPromise.FULFILLED){
setTimeout(()=>{
onFULFILLED(this.result)
})
}
if(this.status == MyPromise.REJECTED){
setTimeout(()=>{
onREJECTED(this.result)
})
}
})
}
all(arr){
if(!Array.isArray(arr)){
throw new Error('不是数组')
}
return new MyPromise( (resolve,reject) =>{
let resolveValues = [];
let num = 0;
arr.forEach((item,index)=>{
item.then( result =>{
resolveValues[index] = result;
num ++;
if(resolveValues.length == arr.length){
return resolve(resolveValues)
}
},(error)=>{
return reject(error)
})
})
})
}
rece(arr){
if(!Array.isArray(arr)){
throw new Error('不是数组')
}
return new MyPromise( (resolve,reject) =>{
arr.forEach((item,index)=>{
item.then( result =>{
return resolve(result)
},(error)=>{
return reject(error)
})
})
})
}
}
console.log('第一步')
let MyPromise = new MyPromise((resolve,reject)=>{
console.log('第二步')
resolve('第一次');
console.log('第四步')
});
MyPromise.all([com1(),com2()]).then(res =>{
console.log(res)
},(err)=>{
console.log(err)
})
function com1(){
return new MyPromise( (resolve,reject)=>{
// throw new Error('宝错了')
setTimeout( ()=>{
resolve('com1')
})
})
}
function com2(){
return new MyPromise( (resolve,reject)=>{
setTimeout( ()=>{
resolve('com2')
})
})
}
// MyPromise.then(
// result => console.log(result),
// result => console.log(result.messages)
// ).then(
// result => console.log(result),
// result => console.log(result.messages)
// )
```