浅析Promise原理

Promise原型对象

在浏览器控制台输入如下代码,可以看到Promise原型对象信息。

var p = new Promise(()=>{});
console.log(p)

Promise原型
Promise原型上有catchfinallythen等方法。同时Promise内部维护了两个属性值statusvalue

Promise构造方法

再看Promise的构造方法,如下图
在这里插入图片描述
构造函数有allallSettledfinallyracerejectresolve等方法。

简单实现

构造函数实现总结:

  1. 构造函数接受一个函数executor,并立即执行;
  2. executor函数接受两个参数,一个是resolve函数,一个是rejected函数,用于后续回调执行;
  3. promise对象的then方法中的第一个参数(函数)是状态变为fulfilled时的回调。
  4. resolve函数被调用时,会触发then方法中的回调函数的指定。
const PENDING = 'pending';
const FULFILLED = 'fullfilled';
const REJECTED = 'rejected';
function Promise(executor) {
  this.status = PENDING;
  this.value = undefined;

  this.onResolvedCallback = []; //成功状态下的回调函数集合
  this.onRejectedCallback = [];

  function resolve(value) {
  };
  
  function reject() {
  };
  
  executor(resolve, reject);
}
const PENDING = 'pending';
const FULFILLED = 'fullfilled';
const REJECTED = 'rejected';
function Promise(executor) {
  this.status = PENDING;
  this.value = undefined;

  this.onResolvedCallback = []; //成功状态下的回调函数集合
  this.onRejectedCallback = [];

  function resolve(value) {
    if(this.status === PENDING) {
      this.status = FULFILLED;
      this.value = value;
      // 触发后续then方法中的回调方法执行
      onRejectedCallback.forEach(onResolved => {
        onResolved(value)
      });
    }
  };
  
  function reject() {
  };
  
  try { // 考虑到执行executor的过程中有可能出错,所以我们用try/catch块给包起来,并且在出错后以catch到的值reject掉这个Promise
    executor(resolve, reject) // 执行executor
  } catch(e) {
    reject(e)
  }
}
``

参考

https://www.jianshu.com/p/b4f0425b22a1
https://github.com/xieranmaya/blog/issues/3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章