03JS基础_手写Promise源码

一、Promise类核心逻辑实现

1、myPromise

// 因为这个状态我们需要频繁去使用,所以将它定义为常量
// 定义成常量的好处: 当我们去使用常量的时候,这个编辑器是我们代码提示的,如果每次在用这个状态的时候写这个字符串,而字符串是没有提示的,所以定义成常量他的最终目的是为了复用而且代码更紧实
const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

// 因为Promise是一中类,通过class创建一个名为MyPromise的类
class MyPromise {
  // 通过构造函数constructor来接收这个执行器(executor)
  constructor (executor) {
    //  这个执行器是立即执行的,所以我们去调用它
    // executor()

    //这个执行器指的就是回调函数,我们需要去传递两个参数resolve和reject
    // 因为是通过箭头函数访问,所以我们要添加上 this.
    executor(this.resolve, this.reject)
    }

  // 因为resolve和reject就是用来更改状态的,而状态是每一个Promise独有的,所以状态属性要定义成实例属性
  // promise 状态 
  status = PENDING;  // 默认状态: 等待

  // 需要将这两个属性定义为实例属性(声明两个属性)
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;


  // 添加一个resolve函数,他的属性是一个箭头函数
  // 定义为箭头函数的原因:  将来在使用resolve和reject时候,是直接调用的,如果直接调用一个函数,而这个函数是普通函数的话,那这个函数里面的this就是undefined
  // 通过箭头函数就让函数的this指向实例对象也就是Promise对象
  // 如果调用resolve,就需要向他传递一个参数,而这个值我们把它命名为成功之后的值value
  resolve = value => {
    // 如果状态不是等待 阻止程序向下执行
    // 因为一旦状态确定就不可更改,所以只能更改等待pending状态
    if (this.status !== PENDING) return;
    // 将状态更改为成功
    this.status = FULFILLED;

    // 保存成功之后的值(因为我们要在then方法中拿)
    this.value = value;
  }

  // 添加一个reject函数,他的属性是一个箭头函数
  // 如果调用reject,就需要向他传递一个参数,而这个值我们把它命名为失败的原因reason
  reject = reason => {
    // 如果状态不是等待 阻止程序向下执行
    if (this.status !== PENDING) return;
    // 将状态更改为失败
    this.status = REJECTED;

    // 保存失败后的原因
    // 让this.reason等于reject函数的这个参数reason
    this.reason = reason;
  }

  // 定义这个then方法,并且把他放到原型当中,这个then接收两个参数,一个是成功回调,一个是失败回调
  then (successCallback, failCallback) {
    // 判断状态
    // 如果状态成功,我们就要调用successCallback/成功回调
    if (this.status === FULFILLED) {
      // 因为在resolve中保存了this.value,所以我们在调用成功回调的时候就可以拿到这个this.value
      successCallback(this.value);
    // 如果状态成功,我们就要调用failCallback/失败回调
    }else if (this.status === REJECTED) {
      // 因为在reject中保存了this.reason,所以我们在调用失败回调的时候就可以拿到这个this.reason
      failCallback(this.reason);
    }
  }
}


// 验证Promise能否使用,使用我们要将Promise进行导出,当前我们在Load环境下,所以我们需要CommonJS的回调语法
module.exports = MyPromise;

2、index


/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

//导入当前文件夹下的myPromise.js文件,再通过const保存导入的这个文件
const MyPromise = require('./myPromise');


// promise的使用方式
// 创建一个promise对象, 通过new去执行promise, 在执行这个类的时候,需要去传递一个回调函数,这个回调函数称之为执行器,这个执行器会立即执行
// 这个回调函数有两个参数,分别是resolve和reject,这两个参数其实是两个函数,调用resolve或者调用reject,实际上是更改Promise的状态
// new Promise((resolve, reject) => {
// let promise = new Promise((resolve, reject) => {

// 之前我们是用的new的Promise对象,现在要用自己定义的myPromise对象
let promise = new MyPromise((resolve, reject) => {
// 当我们创建了一个Promise之后,可以创建一个变量去接收他
  // 传递的参数,传递给resolve的就是成功的值,传递给reject就是失败的值
  resolve('成功')
  reject('失败')
})

// 在promise下面可以创建一个then方法,这个then方法的作用是给他传递两个回调函数,第一个回调函数是成功,第二个回调函数是失败
// 在then方法中,第一个回调函数当中,第一个参数就是成功之后的那个值value,第二个参数就是失败之后的那个值reason
promise.then(value => {
  // 如果当前调用成功了,我们就把成功的这个值输出一下
  console.log(value)
}, reason => {
  // 如果当前调用失败了,我们就把这个失败的原因给他输出一下
  console.log(reason)
})


回顾刚刚做的事情:

  1. 在new promise的时候传递了一个执行器进入,'resolve & reject’这个函数就是一个执行器
  2. 既然说他是一个类,我们通过class创建了一个名为MyPromise的类,通过constructor把这个执行器接收到了,这个执行器是立即执行的,所以在这里马上调用我们的这个执行器
  3. 这个执行器有三种状态:分别是等待/pending、成功/fulfilled、失败/rejected,我们在Promise中定义了一个状态,这个状态默认是pending,我们还声明成功之后的值是什么,失败之后的原因是什么
  4. 当我们去调动resolve时候去更改这个状态,这个状态一旦确认就是不可更改的,所以需要先判断这个状态是不是pending,如果这个状态不是pending,那这个状态是不能更改的,直接return,组织代码继续向下执行; reject也是一样的,首先判断这个状态,然后更改这个状态;这个状态更改之后,还要去保存一下失败的原因,resolve里面同样需要保存一下成功之后的值
  5. 这个then方法要做的事情非常简单,先判断一下Promise的状态,如果状态成功,就调用成功回调,如果状态失败,就调用失败回调,如果调动回调函数,需要将成功的值/失败的原因传递给回调函数,这样Promise的调用者(Promise.then(value=>{}))就可以拿到Promise的执行的结果
  6. 以上是最基本的Promise实现



二、在Promise类中加入异步逻辑

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    executor(this.resolve, this.reject)
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;

  // 为了将成功/失败回调临时存储起来,所以添加实例属性
  // 成功回调
  successCallback = undefined;
  // 失败回调
  failCallback = undefined;

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;

    // 判断成功回调是否存在 如果存在 调用
    this.successCallback && this.successCallback(this.value);
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;

    // 判断失败回调是否存在 如果存在 调用
    this.failCallback && this.failCallback(this.reason);
  }

  then (successCallback, failCallback) {
    // 判断状态
    if (this.status === FULFILLED) {
      successCallback(this.value);
    }else if (this.status === REJECTED) {
      failCallback(this.reason);

    // 判断等待的状态,也就是处理异步情况
    } else {
      // 等待

      // 将成功回调和失败回调临时存储起来,因为现在不知道是成功还是失败回调
      this.successCallback = successCallback
      this.failCallback = failCallback
    }
  }
}

module.exports = MyPromise;


2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');


let promise = new MyPromise((resolve, reject) => {
  // 在myPromise执行器当中添加一个延时器setTimeout,让resolve两秒钟之后再执行
  // 执行顺序: 从上到下依次执行,首先创建一个MyPromise的实例对象,这个执行器会立即执行,当执行到异步代码setTimeout时候,总线程的代码不会等待异步线程的代码执行完成之后再执行的,而是立即执行,当总现场当中的代码执行完成之后,再去执行异步代码; Promise.then会马上执行,并且判断this.status的状态,由于当前的status并没有执行resolve或者reject,所以当then方法执行的时候,status的状态一定是等待,但是对于statue暂时只判断了成功和失败的状态,并没有判断等待的状态,也就是说没有处理异步情况
  setTimeout(() => {
    resolve('成功')
  }, 2000)
  // reject('失败')
})
  
promise.then(value => {
  console.log(value)
}, reason => {
  console.log(reason)
})

回顾异步情况的处理: 当我们在执行器(MyPromise)当中加入异步代码的时候,由于异步代码没有立即执行,他是延迟两秒执行,这时候这个promise.then方法会立即执行,执行then方法的时候需要判断状态,由于我们没有调用resolve或reject,所以他暂时是等待状态,我们就需要把成功和失败的回调函数临时存储起来,再去判断成功函数和失败函数是否存在,如果存在就去调用它; (在命令行工具中,成功的状态并不是立即输出的,而是等待了两秒再输出的)




三、实现then方法多次调用,调用添加多个处理函数

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    executor(this.resolve, this.reject)
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  // successCallback = undefined;
  // 因为只有是数组才能存储多个回调函数
  successCallback = [];
  // 失败回调
  // failCallback = undefined;
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;

    // this.successCallback && this.successCallback(this.value);
    // 因为数组中存储了多个回调函数,所以需要循环这个数组,然后在循环的过程中去调用回调函数
    // wile循环  当数组的长度不等于0的时候,就调用回调函数
    // shift弹出我们需要的回调函数执行, shift()()第一个小括号代表低啊用shift()的值
    // shift方法是删除值,每执行一个删除一个,最终这个长度会变成0,变成0的时候就没有回调函数了,循环条件不成立,循环体就会停止执行
    while(this.successCallback.length) this.successCallback.shift()(this.value)
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    // this.failCallback && this.failCallback(this.reason);
    while(this.failCallback.length) this.failCallback.shift()(this.reason)
  }

  then (successCallback, failCallback) {
    // 判断状态
    if (this.status === FULFILLED) {
      successCallback(this.value);
    }else if (this.status === REJECTED) {
      failCallback(this.reason);
    } else {
      // 等待
      // this.successCallback只是一个普通属性,他每次只能存储一个回调函数,这时候就不符合我们的需求
      // this.successCallback = successCallback
      // 调用push方法将成功的回调函数push监区
      // 现在多个then方法已经被存在数组当中了
      this.successCallback.push(successCallback)

      // this.failCallback = failCallback
      this.failCallback.push(failCallback);
    }
  }
}


module.exports = MyPromise;


2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');


let promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功 .....')
  }, 2000)
  // resolve('成功')
  // reject('失败')
})
  
// 当then方法被调用的时候,每一个then方法当中的回调函数都是要被执行的
// 现在调用了同一个Promise下的三次then方法
// 判断是同步还是异步的情况,如果状态已经是成功或者失败的,那就可以直接调用成功/失败回调函数; 如果是异步的情况,那我们就需要把这三个的每一个异步情况存储起来,当状态变为成功或者失败的时候, 我们再依次去调用它里面的回调函数,这个异步的情况需要去特殊处理一下
promise.then(value => {
  console.log(1)
  console.log(value)
}, (reason) => {
  console.log(reason)
})

promise.then(value => {
  console.log(2)
  console.log(value)
}, (reason) => {
  console.log(reason)
})

promise.then(value => {
  console.log(3)
  console.log(value)
}, (reason) => {
  console.log(reason)
})

回顾刚刚做的事情:

  1. promise下面的then方法是可以被多次调用的,当他的状态变为成功/失败的时候,他里面的所对应的回调函数是要依次被调用的
  2. 调用的方式根据同步和异步分为两种情况: 如果是同步的情况,在判断的时候他已经有状态了,直接去调用它的回调函数就可以了
  3. 如果是异步的情况,需要将这些回调函数临时存储起来,当状态变为成功或者失败的时候,通过循环依次调用其回调函数



四、实现then方法的链式调用(一)

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    executor(this.resolve, this.reject)
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length) this.successCallback.shift()(this.value)
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while(this.failCallback.length) this.failCallback.shift()(this.reason)
  }

  then (successCallback, failCallback) {
    // then方法返回Promise对象,我们才可以链式调用then
    // 传递一个执行器进入,这个执行器是立即执行的
    // 实现了第一个需求,then方法就可以返回Promise了,then方法就可以实现链式调用了
    // 传入两个参数
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        // successCallback(this.value);
        // 拿到成功调用的这个返回值
        let x = successCallback(this.value);
        // 把回调函数的返回值传递给下一个回调函数
        resolve(x);
      }else if (this.status === REJECTED) {
        failCallback(this.reason);
      } else {
        // 等待
        this.successCallback.push(successCallback)
        this.failCallback.push(failCallback);
      }
    });

    // 通过return关键字,返回Promise2
    return promsie2;
  }
}


module.exports = MyPromise;


2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');


let promise = new MyPromise((resolve, reject) => {
  // setTimeout(() => {
  //   resolve('成功 .....')
  // }, 2000)
  resolve('成功')
  // reject('失败')
})
  
// Promise下面的then方法是可以被链式调用的
promise.then(value => {
  console.log(value)
  // 比如我们链式调用一个then方法,在then方法中传入一个回调函数
  // 假如我们在return中返回100,那下面的这个value的值就是100
  return 100;
// 后面then方法的回调函数拿到的值,实际上是上一个then方法的回调函数返回的值
}).then(reason => {
  //在这个then方法当中我们要输出value这个参数的值 => 这个value的值,取决于上一个then方法的在Promise中的返回值
  console.log(reason)
})

// 需要实现的功能: 当这个代码执行的时候,会先输出'成功',这个'成功'是在Promise中传递过来的; 再输出'100', 这个'100'是上一个then方法回调函数的返回值100; 这样一个功能分为两个步骤来实现: 第一步要实现then方法的链式调用, 第二步是如何把上一个then方法的回调函数返回值传递给下一个回调函数

回顾刚刚做的事情:

  1. then方法可以被链式调用,要实现链式调用,then方法必须要返回Promise对象
  2. 所以我们创建了一个promise对象,并且在后面给他返回了
  3. 还要把上一个回调函数的返回值传递给下一个then方法的成功回调
  4. 这时候需要先找到一个then方法的Promise对象,实际上就是我们返回的这个Promise2
  5. 当我们调用Promise2里面的这个resolve时,把x传递给他,实际上就是把x传递给下一个then方法的回调函数
  6. 这样的话我们就实现了then方法的链式调用以及then方法值的传递



五、实现then方法的链式调用(二)

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    executor(this.resolve, this.reject)
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length) this.successCallback.shift()(this.value)
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while(this.failCallback.length) this.failCallback.shift()(this.reason)
  }

  then (successCallback, failCallback) {
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        let x = successCallback(this.value);
        // 判断 x 的值是普通值还是promise对象
        // 如果是普通值 直接调用resolve ,把这个普通值传递给下一个对象
        // 如果是promise对象 查看promsie对象返回的结果 
        // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
        // resolve(x);
        // 把这些内容写在一个公共的函数当中,当需要的时候我们去调用这个函数就可以了

        // 定义一个名为resolvePromise的函数(解析Promise),调用这个函数的时候需要传递 x ,因为我们要判断他的类型
        resolvePromise(x, resolve, reject)
      }else if (this.status === REJECTED) {
        failCallback(this.reason);
      } else {
        // 等待
        this.successCallback.push(successCallback)
        this.failCallback.push(failCallback);
      }
    });

    return promsie2;
  }
}

// 定义resolvePromise这个方法
// 通过function创建resolvePromise这个函数,这个函数接收三个参数
function resolvePromise (x, resolve, reject) {
  // 在当前这个方法当中,我们要判断x的类型,是普通值,还是Promise对象(判断x是不是Promise这个类的实例) instanceof / 属于
  if (x instanceof MyPromise) {
    // 如果x属于Promise实例对象,需要调用Promise下面的then方法,去查看Promise的状态
    // 如果这个Promise状态是成功的,会调用第一个回调函数,失败的话会调用第二个
    // x.then(() => {}, () => {})

    // 如果成功就调用成功的这个值,调用resolve这个回调函数把值传递下去; 如果失败就找到失败的原因,调用reject将失败的原因传递下去
    // x.then(value => resolve, reason => reject(reason))
    //简化: 调用x.then方法,如果调用成功,让他帮我去调用resolve,并且让他把我需要的参数传递过去; 如果失败,让他去调用reject,并且把失败的原因传递下去
    x.then(resolve, reject);
  } else {
    // 如果是普通值,直接调用resolve,把这个值直接传递给下一个Promise对象
    resolve(x);
  }

}


module.exports = MyPromise;


2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');


let promise = new MyPromise((resolve, reject) => {
  // setTimeout(() => {
  //   resolve('成功 .....')
  // }, 2000)
  resolve('成功')
  // reject('失败')
})

// 测试  返回一个Promise对象
// 声明一个名为other的函数
function other () {
  // 这里面返回一个promise,传递一个执行器进去
  return new MyPromise((resolve, reject) => {
    // 直接调用resolve
    resolve('other')
  });
}


// 在链式调用then方法的时候,在then方法的回调当中,我们可以返回一个普通值,也可以返回一个Promise对象;
// 如果返回的是普通值的话,我们可以直接调用Promise方法,把这个普通值传递给下一个Promise对象
// 如果在这个地方返回的是Promise对象的话,我们要先去查看这个Promise的状态,如果这个Promise的状态是成功的,我们要去调用resolve方法把这个成功的状态传递给下一个Promise对象; 如果这个Promise对象返回的状态是失败的话,那我们需要调用reject方法把这个失败的原因传递给下一个Promise对象
promise.then(value => {
  console.log(value)
  // return 100;

  // 现在已经定于完成了,需要返回other的调用
  return other ();
  // 当这个回调函数执行的时候,马上去调用other,other会创建Promise对象,创建Promise对象的话会自动运行
  // 拿到成功回调的返回值的时候,再去判断返回值是普通值还是Promise对象,如果是Promise对象的话就查看他的状态,并且把他的状态传递给下一个Promise对象,如果是普通值的话,直接把他的值传递给下一个Promise对象
}).then(reason => {
  console.log(reason)
})

回顾刚刚做的事情: 处理了一个情况: 在then的回调函数当中,返回Promise的情况




六、then方法链式调用识别Promise对象自返回

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    executor(this.resolve, this.reject)
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length) this.successCallback.shift()(this.value)
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while(this.failCallback.length) this.failCallback.shift()(this.reason)
  }

  then (successCallback, failCallback) {
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        // 通过setTimeout创建一个异步代码,这里的作用不是为了延时,而是为了变成异步代码
        setTimeout(() => {
          let x = successCallback(this.value);
          // resolvePromise(x, resolve, reject)
          // 判断 x 和promise2 是否相等,如果相等的话就说明自己返回了自己,出现了promise对象循环调用的情况,就需要走到reject/错误情况; 当前的这个判断要放到resolvePromise方法当中,所以将promise2传递过来
          // 我们这里是在创建MyPromise的过程中获取Promise2是肯定获取不到的,所以我们需要将这部分代码变成代码,先让同步代码执行完成,执行完成之后Promise2就有了,再去执行这个异步代码
          resolvePromise(promsie2, x, resolve, reject)
        }, 0)
      }else if (this.status === REJECTED) {
        failCallback(this.reason);
      } else {
        // 等待
        this.successCallback.push(successCallback)
        this.failCallback.push(failCallback);
      }
    });
    return promsie2;
  }
}

// function resolvePromise (x, resolve, reject) {
// 这里再补一个形参Promise2
function resolvePromise (promsie2, x, resolve, reject) {
  // 在这里可以直接去判断,如果这个Promise2就是then方法返回的Promise,和我们成功之后返回的Promise相等的话,就是自己返回了自己,就走到reject情况
  if (promsie2 === x) {
    // 创建一个错误提示信息,并且return阻止代码向下执行
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  } 

  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }

}


module.exports = MyPromise;

2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');


let promise = new MyPromise((resolve, reject) => {
  // setTimeout(() => {
  //   resolve('成功 .....')
  // }, 2000)
  resolve('成功')
  // reject('失败')
})

function other () {
  return new MyPromise((resolve, reject) => {
    resolve('other')
  });
}



// 当链式调用then方法的时候,在then方法的回调函数当中,是可以返回Promise对象的, 但是有一种情况是例外的: 在then方法的回调函数当中,不能返回当前then方法他所返回的Promise对象的; 如果你返回了当前then方法返回的Promise对象,这时候就发生了Promise对象的循环调用,这种程序是不被允许的,程序就会报错
// 演示报错情况
// 创建test.html文件,使用系统给我们的提供的Promise对象来演示这个错误

/*
// 如何将这种情况识别出来,然后给调用者报错
promise.then(value => {
  console.log(value)
  return other ();
}).then(reason => {
  console.log(reason)
})
*/

// 测试Promise对象的循环调用报错情况
// 声明变量p1
let p1 = promise.then(value => {
  console.log(value)
  // return other ();
  // 返回p1
  return p1;
})

// 报的错误会传递给后面then失败的回调当中,所以我们继续调用p1.then,并且传递一个失败的回调函数
// .then(reason => {
p1.then(value => {
  console.log(value);
}, reason => {
  // 输出失败的原因
  // console.log(reason)
  // 拿到这个错误本身
  console.log(reason.message)
})

目前为止,我们在我们自己的promise当中就能够识别出,自己返回自己的情况了,如果发生了这种情况,我们就能把这种错误抛出来,告诉promise的调用者,是不能这样使用的




七、捕获错误及then链式调用其他状态代码补充

1、myPromise

// const { fail } = require("node:assert");

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    // 因为在构造函数当中,调用了找个执行器,所以我们使用try catch
    try {
      // 我们需要使用这个执行器,如果这个执行器发生错误,他就会走到catch这个地方
      executor(this.resolve, this.reject)
    // 传入一个错误对象
    }catch (e) {
      // 如果这个代码走到了catch,我们就去调用reject,让这个状态变为错误的状态,把这个错误的原因传递过去
      this.reject(e);
    }
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    // while(this.successCallback.length) this.successCallback.shift()(this.value)
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    // while(this.failCallback.length) this.failCallback.shift()(this.reason)
    // 因为调用resolve & reject不需要再去传值了,我们可以直接调用这个函数
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          
          // 需要捕获successCallback函数的执行错误 try catch
          try{
            let x = successCallback(this.value);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            // 如果这个函数在执行过程中发生了错误,我们就手动调用下一个Promise的reject方法,我们要把这个信息传递给下一个Promise的回调函数
            reject(e);
          }
        }, 0)
      }else if (this.status === REJECTED) {
        // failCallback(this.reason);

        // 当前我们只处理了成功回调的情况,没有处理失败回调的情况
        setTimeout(() => {
          try{
            let x = failCallback(this.reason);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      } else {
        // 等待

        // this.successCallback.push(successCallback)
        // 如果我们把回调函数push到数组当中,我们是没有办法对失败回调的情况处理的
        // 所以我们push一个函数进去
        this.successCallback.push(() => {
          // 再调用这个回调
          // successCallback()

          // 这个时候我们就可以对他进行处理了(成功的回调)
          setTimeout(() => {
            try{
              let x = successCallback(this.value);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });

        // this.failCallback.push(failCallback);
        this.failCallback.push(() => {
          // failCallback()
          // 再处理一下失败的回调
          setTimeout(() => {
            try{
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
      }
    });
    return promsie2;
  }
}

function resolvePromise (promsie2, x, resolve, reject) {
  if (promsie2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  } 

  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}


module.exports = MyPromise;

2、index


/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');

// 在我们这个MyPromise中,我们是没有做任何错误处理的,为了程序的健壮性,还是有必要捕获错误,处理错误
// 第一个处理的错误就是这个执行器,当执行器当中的代码在执行的过程中,发生错误的时候,我们让这个Promise的状态变成失败的状态,也就是then方法的第二个参数中捕获这个错误
let promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功 .....');
  }, 2000)

  // 通过throw来抛出一个错误,错误原因就写上执行器错误
  // throw new Error('executor error')

  // resolve('成功')
  // reject('失败')
});


// 需要处理的第二个捕获错误的地方就在于: 这个then方法里面的回调函数,如果这个回调函数在执行过程中报错了,那么这个错误也要捕获到,当这个then里面的回调函数在执行过程中发生错误,那么这个报错要在下一个then方法的回调当中捕获到
promise.then(value => {
  console.log(value);

  // 在这里通过throw抛出一个错误
  // throw new Error('then error')

  // 在异步调用测试成功以后,我们再返回一个 aaa
  return 'aaa';
  // 这个代码执行之后,我们期望的结果: 两秒钟之后返回一个成功,并且在下一个then里去输出这个aaa

}, reason => {
  // console.log(reason)
  // 输出错误的内容
  // console.log(reason.message);
  // => undefined

  // 去掉message
  console.log(reason);
  // => 失败


  // 我们在这里return一个值,看看这个值能不能跑到下一个then的成功回调当中
  return 10000;
  // 如果在失败回调当中,我们返回普通值或者Promise他都是能够处理的
// 调用then方法
}).then(value => {
  // 输出这个value
  console.log(value)
  // => 10000
});

/*
// 把这个then方法再复制一遍
.then(value => {
  console.log(value);
}, reason => {

  // 检查错误是否是在下一个then方法的回调当中捕获到的
  // console.log('aaaa')
  console.log(reason.message);
})
*/




八、将then方法的参数变成可选参数

1、myPromise

// const { fail } = require("node:assert");

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    // 因为在构造函数当中,调用了找个执行器,所以我们使用try catch
    try {
      // 我们需要使用这个执行器,如果这个执行器发生错误,他就会走到catch这个地方
      executor(this.resolve, this.reject)
    // 传入一个错误对象
    }catch (e) {
      // 如果这个代码走到了catch,我们就去调用reject,让这个状态变为错误的状态,把这个错误的原因传递过去
      this.reject(e);
    }
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    // while(this.successCallback.length) this.successCallback.shift()(this.value)
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    // while(this.failCallback.length) this.failCallback.shift()(this.reason)
    // 因为调用resolve & reject不需要再去传值了,我们可以直接调用这个函数
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    // 在then方法内部,我们要判断then方法内部有没有参数,如果没有我们就给他补一个参数(value => value)
    successCallback = successCallback ? successCallback : value => value;
    // 同上,我们也要判断是否存在参数,如果不存在我们就给他补一个函数,这个函数的形参就是失败的原因
    // 在函数体当中通过throw将这个错误的原因传递下去
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          
          // 需要捕获successCallback函数的执行错误 try catch
          try{
            let x = successCallback(this.value);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            // 如果这个函数在执行过程中发生了错误,我们就手动调用下一个Promise的reject方法,我们要把这个信息传递给下一个Promise的回调函数
            reject(e);
          }
        }, 0)
      }else if (this.status === REJECTED) {
        // failCallback(this.reason);

        // 当前我们只处理了成功回调的情况,没有处理失败回调的情况
        setTimeout(() => {
          try{
            let x = failCallback(this.reason);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      } else {
        // 等待

        // this.successCallback.push(successCallback)
        // 如果我们把回调函数push到数组当中,我们是没有办法对失败回调的情况处理的
        // 所以我们push一个函数进去
        this.successCallback.push(() => {
          // 再调用这个回调
          // successCallback()

          // 这个时候我们就可以对他进行处理了(成功的回调)
          setTimeout(() => {
            try{
              let x = successCallback(this.value);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });

        // this.failCallback.push(failCallback);
        this.failCallback.push(() => {
          // failCallback()
          // 再处理一下失败的回调
          setTimeout(() => {
            try{
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
      }
    });
    return promsie2;
  }
}

function resolvePromise (promsie2, x, resolve, reject) {
  if (promsie2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  } 

  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}


module.exports = MyPromise;

2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');

let promise = new MyPromise((resolve, reject) => {
  // resolve('成功')
  reject('失败')
});


// 在Promise当中,我们链式调用then方法,前两个then方法当中我们不传递任何参数,在第三个函数当中我们才去传递成功的回调函数,将value输出
// promise.then().then().then(value => console.log(value))
// 在第三个then方法中给他传递一个失败的函数,将失败的原因打印出来
promise.then().then().then(value => console.log(value), reason => console.log(reason))

3、test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise 测试</title>
  </head>
  <body>
    <script>
      var promise = new Promise(function (resolve, reject) {
        resolve(100)
      });

      promise
        // Promise下面的then方法链式调用了三次
        // 前两次调用的时候,没有传递任何参数
        // 在这种状态下,这个Promise的状态会依次向后传递,这个then会一直传递给下一个有回调函数的then方法, 也就是说第三次的这个then会拿到这个Promise的这个then方法
        // .then()
        // 当我们在这里不传递任何参数的时候,等同于这样的代码: 我们在这里传递一个回调函数,这个回调函数有一个形参value,在函数体中我们可以直接返回这个value
        .then(value => value)
        // .then()
        // 在第二个Promise中传递相同的状态,这样的话Promise就可以一层一层向后传递了,
        .then(value => value)
        // 第三次传递了一个成功的回调函数
        .then(value => console.log(value))
        // 在then方法内部,我们要判断then方法内部有没有参数,如果没有我们就给他补一个参数(value => value)
    </script>
  </body>
</html>

当我们调用then方法的时候,这个then可以不传递参数,这个Promise的状态会依次向后传递,直到传递给有回调函数的then方法




九、Promise.all方法的实现

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    try {
      executor(this.resolve, this.reject)
    }catch (e) {
      this.reject(e);
    }
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try{
            let x = successCallback(this.value);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      }else if (this.status === REJECTED) {
        setTimeout(() => {
          try{
            let x = failCallback(this.reason);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      } else {
        // 等待
        this.successCallback.push(() => {
          setTimeout(() => {
            try{
              let x = successCallback(this.value);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try{
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
      }
    });
    return promsie2;
  }

  // 创建一个all方法
  // 因为all方法是静态方法,所以前面要加上一个static,声明all方法是一个静态方法,这个all接收一个数组作为参数,所以传入一个名为array的形参
  static all (array) {
    // 所以我们还要准备一个结果数组,用let关键字声明一个result,这个result的值是一个数组
    let result = [];

    // 解决空值问题
    // 添加一个index变量,初始值为0
    let index = 0;


    // // 通过function声明一个方法,并且接收两个参数
    // function addData (key, value) {
    //   // 在当前这个函数当中我们要拿到这个数组,我们要把下标为key的数组添加到result数组当中,添加的具体值就是value
    //   result[key] = value;

    //   // 解决空值问题
    //   // 当我们调动addData,就让index++
    //   index++;
    //   // 判断index的值和array的长度是否相等,如果相等的话就说明数组当中所有的值都已经执行完了
    //   if (index === array.length) {
    //     // 调用resolve结束这个状态
    //     resolve(result);
    //   }
    // }

    // all方法的返回值是一个Promise对象,传递一个执行器进入,这个执行器包含两个参数
    return new MyPromise((resolve, reject) => {
      // 接下来要传递这个数组,所以我们要循环这个数组,循环之前我们要判断一下他是普通值还是Promise对象,如果是普通值,我们可以直接把他放到结果的数组当中,如果他是一个Promise对象,我们就先去执行这个Promise对象,再将这个结果放到结果的数组当中


      // 需要将addData引入到我们执行器当中,不然是无法拿到 resolve(result)的值
      // 通过function声明一个方法,并且接收两个参数
      function addData (key, value) {
        // 在当前这个函数当中我们要拿到这个数组,我们要把下标为key的数组添加到result数组当中,添加的具体值就是value
        result[key] = value;

        // 解决空值问题
        // 当我们调动addData,就让index++
        index++;
        // 判断index的值和array的长度是否相等,如果相等的话就说明数组当中所有的值都已经执行完了
        if (index === array.length) {
          // 调用resolve结束这个状态
          resolve(result);
        }
      }

      // 接下来就可以通过for循环array,通过let关键字声明一个变量i,

      // 空值的原因: 当前的for循环一瞬间就会执行完成,
      for (let i = 0; i < array.length; i++) {
        // 在循环的过程中,我们要拿到当前值,这个当前值用current来表示
        let current = array[i];
        // 判断current是普通值还是Promise对象
        if (current instanceof MyPromise) {
          // 如果是Promise对象,我们需要先去执行这个Promise对象,拿到这个current,我们去调用它的then方法,然后给他传递一个成功回调一个失败回调
          // 如果走到了成功回调里,我们就直接把这个结果value传递到result里,所以我们通过addDate方法把下标为i的值传递到result里面,这个具体的值就是value
          // 如果走到了失败回调里,如果有一个失败,我们就让all方法当前返回的这个状态是失败的,我们把失败的原因传递过去

          // 当时我们当前存在异步操作,没有等待p1等异步操作,
          current.then(value => addData(i, value), reason => reject(reason))
        } else{
          // 如果是普通值
          // 接下来我们就可以把下标为i的添加到result数组当中,这个值就是array[i]
          addData(i, array[i]);
        }
      }
      // 循环完成之后,我们就可以调用resolve方法,并且我们要把result传递到外面去

      // 而后我们调用了resolve结束了这个状态,此时p1里面的代码并没有执行完成
      // resolve(result);
    })
  }
}

function resolvePromise (promsie2, x, resolve, reject) {
  if (promsie2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  } 

  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}


module.exports = MyPromise;

2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');

// 传入p1 p2, 将Promise改为MyPromise
function p1 () {
  return new MyPromise(function (resolve, reject) {
    setTimeout(function () {
      resolve('p1')
    }, 2000)
  })
}

function p2 () {
  return new MyPromise(function (resolve, reject) {
    resolve('p2')
  })
}

// 调用MyPromise的all方法,传入a b
// 链式调用then方法,再将result传入控制台
MyPromise.all(['a', 'b', p1(), p2(), 'c']).then(result => console.log(result))
// => [ 'a', 'b', <1 empty item>, 'p2', 'c' ]
// 本应该是p1 p2的情况,但是出现了空值

// => [ 'a', 'b', 'p1', 'p2', 'c' ]

3、test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise 测试</title>
  </head>
  <body>
    <script>
      function p1 () {
        return new Promise(function (resolve, reject) {
          setTimeout(function () {
            resolve('p1')
          }, 2000)
        })
      }
   
      function p2 () {
        return new Promise(function (resolve, reject) {
          resolve('p2')
        })
      }

      // 按照常规执行情况,因为p1有计时器延迟两秒执行,所以会先输出p2,再输出p1;当时因为Promise.all方法,所以会先输出p1,再输出p2,这就是Promise.all方法的作用,他允许我们通过异步代码调用的顺序得到异步代码执行的结果
      // Promise.all的语法: 他接收一个数组作为参数,在这个数组中我们可以填入任何值,包括普通值和Promise对象,这个数组中得到的顺序一定是我们结果的顺序
      // Promise.all方法的返回值也是一个Promise对象,所以我们可以在后面链式调用then方法
      // Promise.all方法有一个特点,在all中的所有Promise对象如果他的状态都是成功的,那么all方法他的结果也是成功的, 如果有一个是失败的,那结果就是失败的
      // 因为Promise.all,所以all方法一定是一个静态方法
      Promise.all(['a', 'b', p1(), p2(), 'c']).then(function (result) {
        // result -> ['a', 'b', 'p1', 'p2', 'c']
      })
    </script>
  </body>
</html>

总结一下:

  1. all方法是解决异步并发问题的,他允许我们运用异步调用的顺序得到异步代码执行的结果
  2. 由于all方法是一个静态方法,所以all用static来进行定义,接收一个数组作为参数,并且all方法的返回值也是一个Promise对象
  3. 在MyPromise我们通过循环的方式,循环传递进来的数组,在循环的过程中我们判断了数组当前值,看一下他是Promise对象还是普通值
  4. 如果是普通值的话,我们直接调用addData方法,把他放到result这个数组当中
  5. 如果他是Promise对象的话,我们先去执行这个Promise对象
  6. 执行这个Promise对象以后,我们看一下这个Promise对象的状态是什么
  7. 如果是成功的状态,我们就调用addData这个方法,把成功之后的值添加到result数组当中
  8. 如果是失败状态的话,让all的这个状态是失败的(all方法的特点,所以的成功才成功,只要有一个失败就失败)
  9. for循环是一瞬间就执行完的,但是执行for循环的过程中执行了异步操作,我们需要等待所有的异步操作,才能去调用resolve这个方法,去结束all方法的状态
  10. 为了解决这个问题,我们在all中添加了index变量,每一次调用addData方法时候都让index++,++之后我们就去判断index的值和array的长度是否相等
  11. 如果相等的话,就说明所有的异步操作都执行完了,这个时候就可以调用resolve方法去结束all方法的状态了,并且result数组这个结果传递出去



十、Promise.resolve方法的实现

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    try {
      executor(this.resolve, this.reject)
    }catch (e) {
      this.reject(e);
    }
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try{
            let x = successCallback(this.value);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      }else if (this.status === REJECTED) {
        setTimeout(() => {
          try{
            let x = failCallback(this.reason);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      } else {
        // 等待
        this.successCallback.push(() => {
          setTimeout(() => {
            try{
              let x = successCallback(this.value);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try{
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
      }
    });
    return promsie2;
  }

  static all (array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof MyPromise) {
          current.then(value => addData(i, value), reason => reject(reason))
        } else{
          addData(i, array[i]);
        }
      }
    })
  }

  // resolve是一个静态方法,接收一个值作为参数
  static resolve (value) {
    // 在resolve内部,我们先要判断一下这个值是不是MyPromise,如果是的话就是Promise对象,直接返回接可以了
    if (value instanceof MyPromise) return value;
    // 如果不是一个Promise对象,只是一个普通值,那就需要创建一个Promise对象,传递一个执行器进去,这个执行器中我们要拿到resolve这个方法,再通过resolve这个方法把value返回就可以了
    // 最后再返回我们的Promise对象(加上return关键字)
    return new MyPromise(resolve => resolve(value))

  }
}

function resolvePromise (promsie2, x, resolve, reject) {
  if (promsie2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  } 

  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}


module.exports = MyPromise;

2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');

function p1 () {
  return new MyPromise(function (resolve, reject) {
    setTimeout(function () {
      resolve('p1')
    }, 2000)
  })
}

function p2 () {
  return new MyPromise(function (resolve, reject) {
    resolve('p2')
  })
}

// 验证resolve方法
// 传递一个普通值进去,链式调用then方法,通过then方法的成功回调拿到这个value,预期: value为100
MyPromise.resolve(100).then(value => console.log(value))
// => 100

MyPromise.resolve(p1()).then(value => console.log(value))
// => p1(延时两秒)

3、test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise 测试</title>
  </head>
  <body>
    <script>
      function p1 () {
        return new Promise(function (resolve, reject) {
          resolve('hello')
        })
      }

      // 调用了Promise的方法,并传递了10进去,在resolve方法内部,会创建一个Promise对象,并且把这个10包裹在这个对象当中,然后把创建出来的这个Promise对象作为resolve这个方法的返回值, 正是因为只有我们才可以在后面链式调用then方法,通过then方法的成功回调函数拿到这个10
      Promise.resolve(10).then(value => console.log(value))

      // Promise方法也可以接收一个Promise对象,在resolve这个方法中他会判断,你给定的这个值是普通值还是Promise对象,如果是Promise对象的话,他会原封不动地将这个Promise对象再作为resolve的返回值,所以我们才能在后面调用then方法,通过then方法的回调函数拿到Promise对象的返回值
      Promise.resolve(p1()).then(value => console.log(value))

      // 实现resolve方法
      // 首先判断给定的这个值是不是Promise对象,如果是我们就原封不动地把这个Promise对象直接返回就可以了,如果不是就直接创建一个Promise对象,把给定的值包裹在Promise对象当中,然后再把这个Promise对象返回就可以了
    </script>
  </body>
</html>

Promise.resolve的作用: 是将给定的值转化为对象,也就是说Promise的返回值就是一个Promise对象,在返回的这个Promise对象当中,会包裹给定的这个值




十一、Finally方法的实现

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    try {
      executor(this.resolve, this.reject)
    }catch (e) {
      this.reject(e);
    }
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try{
            let x = successCallback(this.value);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      }else if (this.status === REJECTED) {
        setTimeout(() => {
          try{
            let x = failCallback(this.reason);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      } else {
        // 等待
        this.successCallback.push(() => {
          setTimeout(() => {
            try{
              let x = successCallback(this.value);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try{
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
      }
    });
    return promsie2;
  }

  // 在myPromise原型中建立一个finally方法,接收一个回调函数作为参数,因为无论当前Promise对象状态是成功还是失败,我们都要调用这个回调函数
  finally (callback) {
    // 在当前这个方法内部,通过this.then方法得到Promise的状态,添加成功/失败回调函数
    // this.then(() => {

    // 如果需要在finally后面链式调用then方法,就需要finally返回一个Promise对象,所以这里通过return返回一个Promise对象
    return this.then(value => {
      // 不管你传递的是普通值还是Promise,都给你转换成Promise,然后执行这个Promise,在then方法的回调当中返回value
      // 这样就可以等待Promise里面的这个callback再去执行了
      // MyPromise.resolve(callback()).then(() => value);
      // 将最终的结果返回出去
      return MyPromise.resolve(callback()).then(() => value);

      // 在成功的回调当中调用callback
      // callback();

      // 只有我们返回成功的值,下面才能接收到这个值
      // return value;
    }, reason => {
      // 返回的错误原因是当前的错误原因
      return MyPromise.resolve(callback()).then(() => { throw reason });

      // 在失败的回调当中调用callback
      // callback();

      // 如果失败了,就把失败的原因传递到下一个then失败回调中去
      // throw reason;
    })
  }

  static all (array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof MyPromise) {
          current.then(value => addData(i, value), reason => reject(reason))
        } else{
          addData(i, array[i]);
        }
      }
    })
  }

  static resolve (value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise(resolve => resolve(value))

  }
}

function resolvePromise (promsie2, x, resolve, reject) {
  if (promsie2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  } 

  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}


module.exports = MyPromise;

2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');

function p1 () {
  return new MyPromise(function (resolve, reject) {
    setTimeout(function () {
      resolve('p1')
    }, 2000)
  })
}

function p2 () {
  return new MyPromise(function (resolve, reject) {
    // reject('p2 reject')
    resolve('p2 resolve');
  })
}

// 测试finally
// 调用p2这个方法,因为p2方法返回的是一个Promise对象,调用finally方法,传递一个函数进去
p2().finally(() => {
  // 输出finally字符串
  console.log('finally')
  // => finally

  // 在finally方法当中,我们其实要再return一个Promise对象,假定返回p1的调用
  return p1();

// 链式调用Promise对象,拿到p2所返回的结果,我们传入两个回调函数(成功/失败)
}).then(value => {
  // 输出成功的结果
  console.log(value)
}, reason => {
  // 输出失败的原因
  console.log(reason)
  // => p2 reject
})

3、test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise 测试</title>
  </head>
  <body>
    <script>
      function p1 () {
        return new Promise(function (resolve, reject) {
          resolve('hello')
        })
      }

      p1().finally(() => {
        console.log('finally')
      }).then(value => console.log(value));

    </script>
  </body>
</html>

finally方法有两个特点:

  • 第一个是无论当前Promise的最终状态是什么,finally方法当中的回调函数始终都会被执行一次
  • 第二个是在finally方法的后面我们可以链式调用then方法拿到当前Promise对象最终返回的结果
  • finally不是静态方法,需要定义在myPromise原型对象身上



十二、Promise.all方法的实现

1、myPromise

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
  constructor (executor) {
    try {
      executor(this.resolve, this.reject)
    }catch (e) {
      this.reject(e);
    }
  }

  // 状态 
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = value => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promsie2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try{
            let x = successCallback(this.value);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      }else if (this.status === REJECTED) {
        setTimeout(() => {
          try{
            let x = failCallback(this.reason);
            resolvePromise(promsie2, x, resolve, reject)
          }catch (e) {
            reject(e);
          }
        }, 0)
      } else {
        // 等待
        this.successCallback.push(() => {
          setTimeout(() => {
            try{
              let x = successCallback(this.value);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try{
              let x = failCallback(this.reason);
              resolvePromise(promsie2, x, resolve, reject)
            }catch (e) {
              reject(e);
            }
          }, 0)
        });
      }
    });
    return promsie2;
  }

  finally (callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value);

    }, reason => {
      return MyPromise.resolve(callback()).then(() => { throw reason });
    })
  }

  // 加入一个catch实例方法,这个方法被定义在原型对象当中
  // 这个方法接收一个参数failCallback
  // catch () {
  // 在catch方法当中,我们去注册这个failCallback
  catch (failCallback) {
    // then方法当中第一个函数是成功回调,我们不传递成功回调,我们传递一个undefined,接下来再传递一个失败回调
    // this.then(undefined, failCallback)
    // 在then后面可以链式调用其他方法
    return this.then(undefined, failCallback)
  }

  static all (array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof MyPromise) {
          current.then(value => addData(i, value), reason => reject(reason))
        } else{
          addData(i, array[i]);
        }
      }
    })
  }

  static resolve (value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise(resolve => resolve(value))
  }
}

function resolvePromise (promsie2, x, resolve, reject) {
  if (promsie2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  } 

  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}


module.exports = MyPromise;

2、index

/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
  2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected
    一旦状态确定就不可更改
  3. resolve和reject函数是用来更改状态的
    resolve: fulfilled
    reject: rejected
  4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  6. 同一个promise对象下面的then方法是可以被调用多次的
  7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/

const MyPromise = require('./myPromise');

function p1 () {
  return new MyPromise(function (resolve, reject) {
    setTimeout(function () {
      resolve('p1')
    }, 2000)
  })
}

function p2 () {
  return new MyPromise(function (resolve, reject) {
    reject('失败')
    // resolve('成功');
  })
}

// 我们调用p2这个方法
p2()
  // 调用Promise下面的then方法,在then方法当中我们传递一个成功的回调函数,并且去输出成功之后的那个值
  .then(value => console.log(value))

  // 接下来去链式调用catch方法,在catch里面输入一个reason,在函数体当中我们调用log方法输出reason
  .catch(reason => console.log(reason))

3、test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise 测试</title>
  </head>
  <body>
    <script>
      function p1 () {
        return new Promise(function (resolve, reject) {
          resolve('hello')
        })
      }

      p1()
        .then(value => console.log(value))
        .catch(reason => console.log(reason))
    </script>
  </body>
</html>

catch方法的作用是: 用来处理Promise最终状态为失败的情况,就是说当我们调用then方法的时候,是可以不传递失败回调的,如果我们不传递失败回调,那这个失败回调就会被catch方法所捕获,会执行出传入到catch方法中的回调函数

实现: 只需要在catch方法内部去调用then方法就可以了,在then方法当中,在成功回调的地方传入undefined,在失败回调的地方传递回调函数,这样的话,就能够执行catch方法中的失败回调了




十三、自测试题

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后海 0_o

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值