• 梳理promise功能逻辑,手写promise及相关方法


    梳理promise功能逻辑,为分步实现promise奠定基础

    • 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、then方法中加入异步处理逻辑
    • 7、同一个promise对象下面的then方法可以被调用多次
    • 8、then方法是可以被链式调用的 ,后面的then方法的回调函数拿到上一个then方法的回调函数的返回值
    • 9、调用识别Promise对象自返回
    • 10、捕获错误及then链式调用其他状态代码补充
    • 11、then方法参数变为可选

    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)
        }
      }
      // promise状态
      status = PENDING;
      // 成功之后的值
      value = undefined;
      // 失败之后的原因
      reason = undefined;
      // 成功回调
      successCallback = [];
      // 失败回调
      failCallback = [];
    
      resolve = value => {
        // 如果状态不是等待 阻止程序向下执行
        if (this.status !== PENDING) {
          return;
        }
        //将状态更改为成功
        this.status = FULFILLED;
        // 保存成功之后的值
        this.value = value;
        // 成功回调是否存在 处理异步
        this.successCallback.forEach( fn => fn());
      }
    
      reject = reason => {
        // 如果状态不是等待,阻止程序向下执行
        if (this.status !== REJECTED) return;
        // 将状态更改为失败
        this.status = REJECTED;
        // 保存失败之后的原因
        this.reason = reason;
        // 如果异步回调存在 处理异步
        this.failCallback.forEach( fn => fn())
      }
    
      then (successCallback, failCallback) {
        successCallback = successCallback ? successCallback : value => value;
        failCallback = failCallback ? failCallback : reason => {throw reason};
        let promise2 = new MyPromise((resolve, reject)=>{
          // 判断状态
          if (this.status === FULFILLED) {
            // 由于这段代码包含在new MyPromise实例化过程中,会立即执行,所以没法立即获取到promise2
            // 因此使用setTimeout变为异步代码,时间是0
            setTimeout(() => {
              try {
                let x = successCallback(this.value);
                // 判断 x 的值是普通值还是promise对象
                // 如果是普通值 直接调用resolve 
                // 如果是promise对象 查看promsie对象返回的结果 
                // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                resolvePromise(promise2, x, resolve, reject);
              } catch (error) {
                reject(error)
              }
            }, 0)
          }else if (this.status === REJECTED) {
            // 由于这段代码包含在new MyPromise实例化过程中,会立即执行,所以没法立即获取到promise2
            // 因此使用setTimeout变为异步代码,时间是0
            setTimeout(() => {
              try {
                let x = failCallback(this.reason);
                // 判断 x 的值是普通值还是promise对象
                // 如果是普通值 直接调用resolve 
                // 如果是promise对象 查看promsie对象返回的结果 
                // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                resolvePromise(promise2, x, resolve, reject);
              } catch (error) {
                reject(error)
              }
            }, 0)
          }else{
            // 等待 异步
            // 将成功回调和失败回调存储起来
            this.successCallback.push(()=>{
              // 由于这段代码包含在new MyPromise实例化过程中,会立即执行,所以没法立即获取到promise2
              // 因此使用setTimeout变为异步代码,时间是0
              setTimeout(() => {
                try {
                  let x = successCallback(this.value);
                  // 判断 x 的值是普通值还是promise对象
                  // 如果是普通值 直接调用resolve 
                  // 如果是promise对象 查看promsie对象返回的结果 
                  // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                  resolvePromise(promise2, x, resolve, reject);
                } catch (error) {
                  reject(error)
                }
              }, 0)
            });
            this.failCallback.push(()=>{
              // 由于这段代码包含在new MyPromise实例化过程中,会立即执行,所以没法立即获取到promise2
              // 因此使用setTimeout变为异步代码,时间是0
              setTimeout(() => {
                try {
                  let x = failCallback(this.reason);
                  // 判断 x 的值是普通值还是promise对象
                  // 如果是普通值 直接调用resolve 
                  // 如果是promise对象 查看promsie对象返回的结果 
                  // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                  resolvePromise(promise2, x, resolve, reject);
                } catch (error) {
                  reject(error)
                }
              }, 0)
            });
          }
        });
        
        return promise2
      }
    
      catch (failCallback) {
        return this.then(undefined, failCallback)
      }
    
      // 阮一峰es6实现
      finally (callback) {
        return this.then(value=>{
          return MyPromise.resolve(callback()).then(()=> value)
        }, reason=>{
          return MyPromise.resolve(callback()).then(()=> {throw reason})
        })
      }
    
      static all (array) {
        let res = []
        let index = 0
        return new MyPromise((resolve, reject)=>{
          array.forEach((item, i)=>{
            if(item instanceof MyPromise){
              item.then(value=>{
                res[i] = value;
                index++;
                if(index === res.length){
                  resolve(res)
                }
              },reason=>{
                reject(reason);
              })
            }else {
              res[i] = item;
            }
          }) 
        })
      }
      
      static race (array) {
        return new MyPromise((resolve, reject)=>{
          array.forEach((item, i)=>{
            if(item instanceof MyPromise){
              item.then(value=>{
                resolve(value)
              },reason=>{
                reject(reason);
              })
            }else {
              resolve(item)
            }
          }) 
        })
      }
      
    
      static resolve (value) {
        if (value instanceof MyPromise ) return value;
        return new MyPromise(resolve => resolve(value))
      }
    }
    
    const resolvePromise = (promise2, x, resolve, reject) => {
      if (promise2 === x ) {
        reject(new TypeError('xxxx'));
        return;
      }
      if ( x instanceof MyPromise) {
        // promise对象
        x.then(value => resolve(value), reason => reject(reason))
      }else {
        // 普通值 
        resolve(x)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
  • 相关阅读:
    django 开启CSRFtoken校验,以及postman实现问题
    keep-alive
    XML - XML学习/XML文件解析器(C++)实现
    小侃设计模式(十一)-享元模式
    收单外包机构备案业务类型汇总分析
    《数据库》第1章 数据库系统概论
    尤雨溪对 2022 Web前端生态趋势是这样看的
    深度估计 双目深度估计+单目深度估计 ONNX运行程序
    有关QT的问题大全
    DolphinScheduler——介绍及架构设计
  • 原文地址:https://blog.csdn.net/qq_41534913/article/details/127810936