首页 > 其他分享 >手写promise

手写promise

时间:2024-05-22 17:54:00浏览次数:24  
标签:resolve const err .# promise result reject 手写

const pending = 'pending'
const fulfilled = 'fulfilled'
const rejected = 'rejected'

class MyPromise {
  #state = pending
  #result = undefined
  #handler = []
  constructor(exector) {
    const resolve = (data) => {
      this.#changeState(fulfilled, data)
    }
    const reject = (reason) => {
      this.#changeState(rejected, reason)
    }
    try {
      exector(resolve, reject)
    } catch (err) {
      reject(err)
    }
  }
  #isPromise(prom){
     return prom!==null && (typeof prom==='object' ||typeof prom==='function') && typeof prom.then==='function'
  }
  #runOne(callback, resolve, reject) {
    if (typeof callback === 'function') {
      try {
        const ret = callback(this.#result)
        if(this.#isPromise(ret)){
          ret.then(resolve,reject)
        }else{
          resolve(ret)
        }
      } catch (err) {
        reject(err)
      }
    } else {
      const callFn = this.#state === fulfilled ? resolve : reject
      callFn(this.#result)
    }
  }
  #run() {
    if (this.#state !== pending) return;
    while (this.#handler.length) {
      const { onFulfilled, onReject, resolve, reject } = this.#handler.shift()
      if (this.#state === fulfilled) {
        this.#runOne(onFulfilled, resolve, reject)
        // if (typeof onFulfilled === 'function') {
        //   try {
        //     const ret = onFulfilled(this.#result)
        //     resolve(ret)
        //   } catch (err) {
        //     reject(err)
        //   }
        // }else{
        //   resolve(this.#result)
        // }
      } else if (this.#state === rejected) {
        this.#runOne(onReject, resolve, reject)
        // if (typeof onReject === 'function') {
        //   const err = onReject(this.#result)
        //   reject(err)
        // }else{
        //   reject(this.#result)
        // }
      }
    }
  }
  #changeState(state, data) {
    if (this.#state !== pending) return;
    this.#state = state
    this.#result = data
    this.#run()
  }
  then(onFulfilled, onReject) {
    return new MyPromise((resolve, reject) => {
      this.#handler.push({
        onFulfilled,
        onReject,
        resolve,
        reject
      })
      this.#run()
    })
  }
  toString() {
    console.log(this.#result)
  }
}

aa = new MyPromise((resolve, reject) => {
  resolve('33333')
})
aa.then(res => {
  console.log(res)
  throw new Error('eeee')
},
  err => {
    console.log(err)
  }).then(res => {
    console.log(res)
  })
// console.log(aa.toString())

 

标签:resolve,const,err,.#,promise,result,reject,手写
From: https://www.cnblogs.com/howhy/p/18206806

相关文章

  • 关于async/await、promise和setTimeout执行顺序
    前段时间领导给我们出了一道题,关于async/await、promise和setTimeout的执行顺序,网上查了查资料,这是头条的一道笔试题,记录一下,加深理解。题目如下:asyncfunctionasync1(){console.log('async1start');awaitasync2();console.log('asnyc1end');}asyncfunc......
  • [ES2024] Manually settle a promise using Promise.withResolvers
    Ifwewanttobeabletomodifythestateofapromisefromoutsidetheconstructor,wecanusethe Promise.withResolvers methodtogetaccesstothepromise,andits resolve and reject functions. //oldapproachletres,rej;constpromise=newPr......
  • Promise 的完全实现
    零、参考资料手把手一行一行代码教你“手写Promise“,完美通过Promises/A+官方872个测试用例手写实现Promise全部实例方法和静态方法,来看看Promise.all、Promise.race和Promise.any都是怎么实现的JS/ES6Promise的不完全实现 一、具体代码exportdefaultcl......
  • JavaScript execute asynchronous functions in Parallel with count and Promise All
    JavaScriptexecuteasynchronousfunctionsinParallelwithcountandPromiseAllInOneJavaScript使用count和Promise并行执行异步函数errorsfunctionpromiseAll<T>(functions:Fn<T>[]):Promise<T[]>{returnnewPromise((resolve,reject)=&......
  • promise(A).catch(f1).then(f2),f1执行后f2回执行吗,为什么
    在JavaScript中,Promise链中的.catch()方法用于捕获前面Promise中的错误,并且无论这个错误是在.then()链中的哪一个环节产生的,.catch()都会捕获到。当错误被.catch()处理之后,如果希望后续的Promise链继续执行,可以这样做。所以对于代码promise(A).catch(f1).then(f2):首先会执行pr......
  • 手写Word2vec算法实现
    1.语料下载:https://dumps.wikimedia.org/zhwiki/latest/zhwiki-latest-pages-articles.xml.bz2【中文维基百科语料】2.语料处理(1)提取数据集的文本下载的数据集无法直接使用,需要提取出文本信息。安装python库:pipinstallnumpypipinstallscipypipinstallgensimp......
  • JavaScript Promise Time Limit Function All In One
    JavaScriptPromiseTimeLimitFunctionAllInOneLeetCode2637.PromiseTimeLimiterrorsfunctiontimeLimit(fn:Fn,t:number):Fn{returnasyncfunction(...args){//letbegin=Date.now();letbegin=performance.now();letresult=......
  • 实验7-使用TensorFlow完成MNIST手写体识别
    VMware虚拟机Ubuntu20-LTSpython3.6tensorflow1.15.0keras2.3.1运行截图:  代码:importosos.environ['TF_CPP_MIN_LOG_LEVEL']='2'importnumpyasnpimporttensorflowastffromtensorflow_core.examples.tutorials.mnistimportinput_datai......
  • 从零手写实现 tomcat-11-filter 过滤器
    创作缘由平时使用tomcat等web服务器不可谓不多,但是一直一知半解。于是想着自己实现一个简单版本,学习一下tomcat的精髓。系列教程从零手写实现apacheTomcat-01-入门介绍从零手写实现apacheTomcat-02-web.xml入门详细介绍从零手写实现tomcat-03-基本的socket实......
  • uniapp 小程序 实现 vue 实现手写签名
    方法一<template><viewclass="signBox"><viewclass="topHint">请在下方空白书写区域内写出您的名字</view><viewclass="btn"><viewclass="saveBtn"@click="save"......