js实现promise

??

new Promise((resolve, reject) => {
    //??????resolve?????reject
}).then((res) => {
    //resolve???????????    
}, (err) => {
    //reject???????????
}).then(res => {
//????then????????promise
//??????????
}).catch(reason => {

});
//?????promise?????then?
//?????????????catch
Promise.all([promise1, ...]).then();

????

??????

????Promise?

1.????????pending?, ‘fulfilled’, ‘rejected’

2.????then???????????

//promise.js
class Promise{
  //?????????
  constructor(excutorCallBack){
    this.status = 'pending';
    this.value = undefined;
    this.fulfillAry = [];
    this.rejectedAry = [];
    //=>??Excutor
    let resolveFn = result => {
      if(this.status !== 'pending') return;
      let timer = setTimeout(() => {
        this.status = 'fulfilled';
        this.value = result;
        this.fulfillAry.forEach(item => item(this.value));
      }, 0);
    };
    let rejectFn = reason => {
      if(this.status !== 'pending')return;
      let timer = setTimeout(() => {
        this.status = 'rejected';
        this.value = reason;
        this.rejectedAry.forEach(item => item(this.value))
      })
    };
    try{
      //????????
      excutorCallBack(resolveFn, rejectFn);
    } catch(err) {
      //=>???????rejected????
      rejectFn(err);
    }
  }
  then(fulfilledCallBack, rejectedCallBack) {
    //resolve?reject???????????
    //??????????????then???????
    this.fulfillAry.push(fulfilledCallBack);
    this.rejectedAry.push(rejectedCallBack);
    //??push???????
  }
}

module.exports = Promise;

????

?????

let Promise = require('./promise');

let p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    Math.random()<0.5?resolve(100):reject(-100);
  }, 1000)
}).then(res => {
  console.log(res);
}, err => {
  console.log(err);
})

????

?? ??????

?????????????????????then??????

  //then??????
  then(fulfilledCallBack, rejectedCallBack) {
    //???????
    typeof fulfilledCallBack !== 'function' ? fulfilledCallBack = result => result:null;
    typeof rejectedCallBack !== 'function' ? rejectedCallBack = reason => {
      throw new Error(reason instanceof Error? reason.message:reason);
    } : null
    //????Promise??????????Promise?
    return new Promise((resolve, reject) => {
      //????this?????Promise????????Promise
      //?????,????
      //???Promise(????return??Promise)?resolve?reject???????????
      //??????????????then???????
      this.fulfillAry.push(() => {
        try {
          //?then??????????
          //?????????
          let x = fulfilledCallBack(this.value);
          //?????????????????????????Promise????
          //?????x???Promise??????then??
          //????Promise,?????Promise?resolve??,
          //?Promise?fulfilAry????,??Promise?then???.?Promise?resolve??
          x instanceof Promise ? x.then(resolve, reject):resolve(x);
        }catch(err){
          reject(err)
        }
      });
      //????
      this.rejectedAry.push(() => {
        try {
          let x = this.rejectedCallBack(this.value);
          x instanceof Promise ? x.then(resolve, reject):resolve(x);
        }catch(err){
          reject(err)
        }
      })
    }) ;
  }
????

?????

let p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    Math.random()<0.5?resolve(100):reject(-100);
  }, 1000)
})

let p2 = p1.then(result => {
  //??then????????Promise
  return result + 100;
})
let p3 = p2.then(result => {
  console.log(result);
}, reason => {
  console.log(reason)
})
????

???????????????????

?????????

??then???catch?????????

  catch(rejectedCallBack) {
    return this.then(null, rejectedCallBack);
  }
????

??Promise.all()

?????Promise.all()

//???????????????
static all(promiseAry = []) {
    let index = 0, 
        result = [];
    return new Promise((resolve, reject) => {
      for(let i = 0; i < promiseAry.length; i++){
        promiseAry[i].then(val => {
          index++;
          result[i] = val;
          if( index === promiseAry.length){
            resolve(result)
          }
        }, reject);
      }
    })
  }
????

??Promise.race()

????race??

static race(promises) {
  return new Promise((resolve, reject) => {
    if (promises.length === 0) {
      return;
    } else {
      for(let i = 0; i < promises.length; i++){
        promises[i].then(val => {
            resolve(result);
            return;
          }
        }, reject);
      }
    }
  });
}
????

??Promise.resolve()

static resolve (value) {
    if (value instanceof Promise) return value
    return new Promise(resolve => resolve(value))
}
????

??Promise.reject()

static reject (value) {
    return new Promise((resolve, reject) => reject(value))
}
????

????

?????????????????Promise???????

class Promise{
  constructor(excutorCallBack){
    this.status = 'pending';
    this.value = undefined;
    this.fulfillAry = [];
    this.rejectedAry = [];
    //=>??Excutor
    let resolveFn = result => {
      if(this.status !== 'pending') return;
      let timer = setTimeout(() => {
        this.status = 'fulfilled';
        this.value = result;
        this.fulfillAry.forEach(item => item(this.value));
      }, 0);
    };
    let rejectFn = reason => {
      if(this.status !== 'pending')return;
      let timer = setTimeout(() => {
        this.status = 'rejected';
        this.value = reason;
        this.rejectedAry.forEach(item => item(this.value))
      })
    };
    try{
      excutorCallBack(resolveFn, rejectFn);
    } catch(err) {
      //=>???????rejected????
      rejectFn(err);
    }
  }
  then(fulfilledCallBack, rejectedCallBack) {
    typeof fulfilledCallBack !== 'function' ? fulfilledCallBack = result => result:null;
    typeof rejectedCallBack !== 'function' ? rejectedCallBack = reason => {
      throw new Error(reason instanceof Error? reason.message:reason);
    } : null

    return new Promise((resolve, reject) => {
      this.fulfillAry.push(() => {
        try {
          let x = fulfilledCallBack(this.value);
          x instanceof Promise ? x.then(resolve, reject ):resolve(x);
        }catch(err){
          reject(err)
        }
      });
      this.rejectedAry.push(() => {
        try {
          let x = this.rejectedCallBack(this.value);
          x instanceof Promise ? x.then(resolve, reject):resolve(x);
        }catch(err){
          reject(err)
        }
      })
    }) ;
  }
  catch(rejectedCallBack) {
    return this.then(null, rejectedCallBack);
  }
  static all(promiseAry = []) {
    let index = 0, 
        result = [];
    return new Promise((resolve, reject) => {
      for(let i = 0; i < promiseAry.length; i++){
        promiseAry[i].then(val => {
          index++;
          result[i] = val;
          if( index === promiseAry.length){
            resolve(result)
          }
        }, reject);
      }
    })
  }
 static race(promiseAry) {
  return new Promise((resolve, reject) => {
    if (promiseAry.length === 0) {
      return;
    }
    for (let i = 0; i < promiseAry.length; i++) {
      promiseAry[i].then(val => {
        resolve(val);
        return;
      }, reject);
    }     
  })
}
static resolve (value) {
    if (value instanceof Promise) return value
    return new Promise(resolve => resolve(value))
}
static reject (value) {
    return new Promise((resolve, reject) => reject(value))
}
}

module.exports = Promise;

   转载规则


《js实现promise》 朝飞 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录