promise的粗糙实现

124 阅读1分钟
function promise(fn) {
  this.pending = "init"; //状态 pending init  error end
  this.value = ""; //正确的值
  this.errValue=''//构造函数错误的值
  this.task = []; //then队列
  this.task.pointer=0//then队列指针
  this.errTask = [];//catch队列
  this.errTask.pointer=0//catch队列指针
  this.then = (fn,fnError) => { //then函数
    const f = () => { //包装函数
        if(this.pending=='end'){ //处理构造函数同步错误
            this.value=fnError( this.errValue,res,rej)
        }else{  //添加then函数
            this.value=fn(this.value,res,rej);
        }
      this.task.pointer++;  //then队列指针自增
      doer(); //then队列指针自增
    };
    this.task.push(f);
    if(this.pending!=='init'){ //触发一次
        doer()
    }
    return this  //把当前对象返还回去
  };
  this.catch = fn => {
    const f = () => {//包装函数
        this.value=fn(this.value);
        this.errTask.pointer++;
        doError();
      };
      this.errTask.push(f);
    if(this.pending=='error'){
        fn(this.value)
    }
     return this  //把当前对象返还回去
  };
  const doer = () => {
    if(this.task[this.task.pointer]){
     this.task[this.task.pointer]()
    }else if(this.task.length>0){
        console.log('执行完毕',this.value,this.task)
    }
  };
  const doError=()=>{
    if(this.errTask[this.errTask.pointer]){
        this.errTask[this.errTask.pointer]()
       }else if(this.errTask.length>0){
           console.log('执行完毕',this.value,this.errTask)
       }
  }
  const res = e => { //内置res函数
    if(this.pending =='init'){
        this.pending = "finish";
        this.value = e;
        doer()
    }else{
        console.log('状态不可返回')
    }
    
  };
  const rej = e => { //内置rej函数
   if(this.pending =='init'){
    this.value = e;
    this.pending = "error";
    doError()
    }else{
        console.log('状态不可返回')
    }
  };
  try{ //只能同步捕获,异步必须调rej
    fn(res, rej);
  }catch(e){
    this.errValue = e;
    this.pending = "end";
    doer()
  }
}

promise的同步捕获在then(fn,fb)的fb函数中,异步捕获只能手动调用reject函数

类似的异步错误处理,参开下图