学习日记-手写promise

236 阅读1分钟

未写完,写完了讲解一下

/*
 value:Promise值
 status:Promise状态 pending等待 resolved完成 rejected报错
 */
class NewPromise {
  constructor(fun) {
    this.value = null;
    this.status = 'pending';
    this.error=null
    this.onFulfilled = [];//完成时数组
    this.onRejected = [];//未完成的数组
    const resolve = (value)=> {
        if(this.status==='pending'){
            this.value=value;
            this.status='resolved'
            this.onFulfilled.forEach(callback=>callback(this.value))
            this.onFulfilled=[]
        }
    };
    const reject = (error)=> {
        if(this.status==='pending'){
            this.error=error;
            this.status='rejected'
            this.onRejected.forEach(callback=>callback(this.error))
            this.onRejected=[]
            throw error
        }
    };
    try{
        fun(resolve,reject)
    }catch(e){
        reject(e)
    }
  }

  then(resolveCall,rejectCall){
    let bindPromise;
    let self = this;
      if(this.status==='pending'){
        //  this.onFulfilled.push(resolve)
        return bindPromise = new NewPromise((resolve, reject) => {
            self.onFulfilled.push((value) => {
              try {
                let x = resolveCall(value);
                resolve(x);
              } catch (e) {
                reject(e);
              }
            });
            // self.onRejected.push((error) => {
            //   try {
            //     let x = rejectCall(error);
            //     resolve(x);
            //   } catch (e) {
            //     reject(e);
            //   }
            // });
          });
      }
      else  if(this.status==='resolved'){
        // resolveCall(this.value)
        return bindPromise = new NewPromise((resolve, reject) => {
            let x = resolveCall(this.value);
            resolve(x)
          });
      }
      else{
        rejectCall(this.error)
      } 
  }

//   static resolve(val) {//静态方法
//     this.status = "resolved";
//     this.value = val;
//     return this
//   }
}
const newPromise=new NewPromise((resolve)=>{
  console.log(1)
    setTimeout(()=>{ 
      console.log(4)
        resolve(111)
    },1000)
    console.log(2)

})
.then(res=>{
   console.log(res)
//    return 100
})
// .then(res=>{
//     console.log(res)
// })
console.log(newPromise)