• 实现Promise的原型方法--前端面试能力提升


    说起Promise大家应该都耳熟能详,我们今天来看下Promise的相关方法

    有如下:
    原型方法:then、catch、finally

    静态方法:resolve、reject、race、all、allSettled、any

    手写实现方法如下:

    实现resolve方法

    promise.resolve('123')实质上就是
    new Promise(resolve=>
    resolve('123')
    })
    
    • 1
    • 2
    • 3
    • 4

    Promise.resolve(value)  将给定的一个值转为Promise对象。

    • 如果这个值是一个 promise ,那么将返回这个 promise ;
    • 如果这个值是thenable(即带有"then" 方法),返回的promise会“跟随”这个thenable的对象,采用它的最终状态;
    • 否则返回的promise将以此值完成,即以此值执行resolve()方法 (状态为fulfilled)。
    • 参考 前端手写面试题详细解答
     class MyPromise {
       
            static PENDING = 'pending'
            static FULFILLED = 'fulfilled'
            static REJECTED = 'rejected'
            constructor(executor) {
       
              this.PromiseState = MyPromise.PENDING
              this.PromiseResult = null
              this.fulfilledCallBacks = []
              this.rejectedCallBacks = []
              try {
       
                executor(this.resolve.bind(this), this.reject.bind(this))
              } catch (error) {
       
                this.reject(error)
              }
            }
            resolve(result) {
       
              if ((this.PromiseState = MyPromise.PENDING)) {
       
                setTimeout(() => {
       
                  this.PromiseState = MyPromise.FULFILLED
                  this.PromiseResult = result
                  for (const callBack of this.fulfilledCallBacks) {
       
                    callBack(result)
                  }
                })
              }
            }
            reject(reason) {
       
              if ((this.PromiseState = MyPromise.PENDING)) {
       
                setTimeout(() => {
       
                  this.PromiseState = MyPromise.REJECTED
                  this.PromiseResult = reason
                  for (const callBack of this.rejectedCallBacks) {
       
                    callBack(reason)
                  }
                })
              }
            }
            then(onFulfilled, onRejected) {
       
              onFulfilled =
                typeof onFulfilled === 'function' ? onFulfilled : (val) => val
              onRejected =
                typeof onRejected === 'function'
                  ? onRejected
                  : (err) => {
       
                      throw err
                    }
              return new MyPromise((resolve, reject) => {
       
                if (this.PromiseState === MyPromise.PENDING) {
       
                  this.fulfilledCallBacks.push(() => {
       
                    setTimeout(() => {
       
                      let x = onFulfilled(this.PromiseResult)
                      x instanceof MyPromise ? x.then(resolve, reject) : resolve(x)
                    })
                  })
                  this.rejectedCallBacks.push(() => {
       
                    setTimeout(() => {
       
                      let x = onRejected(this.PromiseResult)
                      x instanceof MyPromise ? x.then(resolve, reject) : reject(x)
                    })
                  })
                } else if (this.PromiseState === MyPromise.FULFILLED) {
       
                  try {
       
                    setTimeout(() => {
       
                      let x = onFulfilled(this.PromiseResult)
                      x instanceof MyPromise ? x.then(resolve, reject) : resolve(x)
                    })
                  } catch (error) {
       
                    reject(error)
                  }
                } else {
       
                  try {
       
                    setTimeout(() => {
       
                      let x = onRejected(this.PromiseResult)
                      x instanceof MyPromise ? x.then(resolve, reject) : reject(x)
                    })
                  } catch (error) {
       
                    reject(error)
                  }
                }
              })
            }
            //value 要解析为 Promise 对象的值
            static resolve(value) {
       
              //如果是
              if (value instanceof MyPromise) {
       
                return value
              } else if (value && typeof value === 'object' && 'then' in value) {
       
                return new MyPromise((resolve, reject) => {
       
                  value.then(resolve, reject)
                })
              }
              return new MyPromise((resolve) => {
       
                resolve(value)
              })
            }
          }
          const promise1 = MyPromise.resolve(123)
    
          promise1.then((value) => {
       
            console.log(value)
            // expected output: 123
          })
    
          // Resolve一个thenable对象
          var p1 = MyPromise.resolve({
       
            then: function (onFulfill) {
       
              onFulfill('Resolving')
            },
          })
          console.log(p1 instanceof MyPromise) // true, 这是一个Promise对象
    
          setTimeout(() => {
       
            console.log('p1 :>> ', p1)
          }, 1000)
    
          p1.then(
            function (v) {
       
              console.log(v) // 输出"Resolving!"
            },
            function (e) {
       
              // 不会被调用
            }
          )
    
          // Thenable在callback之前抛出异常
          // MyPromise rejects
          var thenable = {
       
            then: function (resolve) {
       
              throw new TypeError('Throwing')
              resolve('Resolving')
            },
          }
    
          var p2 = MyPromise.resolve(thenable)
          p2.then(
            function (v) {
       
              // 不会被调用
            },
            function (e) {
       
              console.log(e) // TypeError: Throwing
            }
          )
    
    • 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

    实现reject方法

    const p=Promise.reject(‘error’)
    相当于下方函数:
    const p=new Promise(reject=>{
    reject(‘11111’)
    })

    Promise.reject()方法返回一个带有拒绝原因的Promise对象。

     class MyPromise {
       
            static PENDING = 'pending'
            static FULFILLED = 'fulfilled'
            static REJECTED = 'rejected'
            constructor(executor) {
       
              this.PromiseState = MyPromise.PENDING
              this.PromiseResult = null
              this.fulfilledCallBacks = []
              this.rejectedCallBacks = []
              try {
       
                executor(this.resolve.bind(this), this.reject.bind(this))
              } catch (error) {
       
                this.reject(error)
              }
            }
            resolve(result) {
       
              if ((this.PromiseState = MyPromise.PENDING)) {
       
                setTimeout(() => {
       
                  this.PromiseState = MyPromise.FULFILLED
                  this.PromiseResult = result
                  for (const callBack of this.fulfilledCallBacks) {
       
                    callBack(result)
                  }
                })
              }
            }
            reject(reason) {
       
              if ((this.PromiseState = MyPromise.PENDING)) {
       
                setTimeout(() => {
       
                  this.PromiseState = MyPromise.REJECTED
                  this.PromiseResult = reason
                  for (const callBack of this.rejectedCallBacks) {
       
                    callBack(reason)
                  }
                })
              }
            }
            then(onFulfilled, onRejected) {
       
              onFulfilled =
                typeof onFulfilled === 'function' ? onFulfilled : (val) => val
              onRejected =
                typeof onRejected === 'function'
                  ? onRejected
                  : (err) => {
       
                      throw err
                    }
              return new MyPromise((resolve, reject) => {
       
                if (this.PromiseState === MyPromise.PENDING) {
       
                  this.fulfilledCallBacks.push(() => {
       
                    setTimeout(() => {
       
                      let x = onFulfilled(this.PromiseResult)
                      x instanceof MyPromise ? x.then(resolve, reject) : resolve(x)
                    })
                  })
                  this.rejectedCallBacks.push(() => {
       
                    setTimeout(() => {
       
                      let x = onRejected(this.PromiseResult)
                      x instanceof MyPromise ? x.then(resolve, reject) : reject(x)
                    })
                  })
                } else if (this.PromiseState === MyPromise.FULFILLED) {
       
                  try {
       
                    setTimeout(() => {
       
                      let x = onFulfilled(this.PromiseResult)
                      x instanceof MyPromise ? x.then
    • 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
  • 相关阅读:
    代码随想录算法训练营day30||332.重新安排行程 ||第51题. N皇后||37. 解数独
    C/C++输出整数部分 2021年12月电子学会青少年软件编程(C/C++)等级考试一级真题答案解析
    Leetcode131. 分割回文串
    Redis【超详解!!!】
    硬盘分哪几种类型及主要参数详解
    IP-guard Web系统远程命令执行漏洞说明
    flutter3-macOS桌面端os系统|flutter3.x+window_manager仿mac桌面管理
    交叉编译嵌入式linux平台的gdb工具
    Linux安装Jenkins
    批量执行insert into 的脚本报2006 - MySQL server has gone away
  • 原文地址:https://blog.csdn.net/helloworld1024fd/article/details/127765778