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

本文介绍了Promise的原型方法如then、catch、finally的实现,以及静态方法resolve、reject、race、all、allSettled、any的详细实现过程。通过理解并手写这些方法,可以提升前端面试中的问题解决能力。
摘要由CSDN通过智能技术生成

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

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

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

手写实现方法如下:

实现resolve方法

promise.resolve('123')实质上就是
new Promise(resolve=>
resolve('123')
})

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

更多面试题解答参见 前端手写面试题详细解答

实现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 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值