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


    说起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 '
    运行
  • 相关阅读:
    在WordPress网站上添加文章分类信息
    【HMS Core】构建SplitBill应用集成多个HMS Core服务,助力您更好的了解华为生态组成
    Apache Tomcat 8.5安装配置教程
    SQL注入漏洞(union + 盲注)
    AI搞钱——工具篇之视频、音频转文字
    计算机中整数的补码表示及二进制数轮
    [安卓APP毕业设计源码]精品基于Uniapp+SSM实现的植物介绍APP[包运行成功]
    IDEA连接DB2数据库自动生成Entity实体类(SpringBoot + Spring JPA + Lombok + DB2)
    DFS 模板:843. n-皇后问题
    物流查询 批量查询物流如何查看快递是否已签收
  • 原文地址:https://blog.csdn.net/helloworld1024fd/article/details/127121519