我如何实现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();

复制代码

1、小试牛刀

初步实现Promise:promise

1.实现三种状态:‘pending’, 'fulfilled', 'rejected'dom

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);
})

复制代码

2、 完成链式效果

最大的难点在于链式调用的实现,具体来讲就是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)
        }
      })
    }) ;
  }
复制代码

测试用例:ui

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)
})
复制代码

简单画图来模拟一下链式调用的内部流程: this

在这里插入图片描述
有了then方法,catch天然而然调用便可:

catch(rejectedCallBack) {
    return this.then(null, rejectedCallBack);
  }
复制代码

3、Promise.all()

接下来实现Promise.all()spa

//为类的静态方法,而不是在原型上
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);
      }
    })
  }
复制代码

4、Promise.race()

接下来是race方法code

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);
      }
    }
  });
}
复制代码

5、Promise.resolve()

static resolve (value) {
    if (value instanceof Promise) return value
    return new Promise(resolve => resolve(value))
}
复制代码

6、Promise.reject()

static reject (value) {
    return new Promise((resolve, reject) => reject(value))
}
复制代码

完整代码

如今手写一个简陋可是功能较为完备的Promise就大功告成了。cdn

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;

复制代码
相关文章
相关标签/搜索