首页 > 其他分享 >手写promise

手写promise

时间:2023-05-12 13:11:36浏览次数:21  
标签:resolve const state promise reject return 手写 data

const PENDING = 'pending'
const FULFILLED = 'fullfilled'
const REJECTED = 'rejected'

class MyPromise {
  state = PENDING
  result = undefined
  handlers = []

  constructor(executor) {
    const resolve = (data) => {
      this.changeState(FULFILLED, data)
    }
    const reject = (reson) => {
      this.changeState(REJECTED, reson)
    }
    try {
      executor(resolve, reject)
    } catch (error) {
      reject(error)
    }

  }

  changeState(state, result) {
    if (this.state !== PENDING) return
    this.state = state
    this.result = result
    this.run()
  }

  isPromiseLike = (value) => {
    if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
      return typeof value.then === 'function'
    }
    return false
  }

  runMocroTask = (func) => {
    if (typeof process === 'object' && typeof process.nextTick === 'function') {
      process.nextTick(func)
    } else if (typeof MutationObserver === 'function') {
      const ob = new MutationObserver(func)
      const textNode = document.createTextNode('1')
      ob.observe(textNode, {
        characterData: true
      })
      textNode.data = '2'
    } else {
      setTimeout(func, 0)
    }
  }

  runOne = (callback, resolve, reject) => {
    this.runMocroTask(() => {
      // 1、对应回调函数不是一个函数 直接把结果返回
      if (typeof callback !== 'function') {
        const settled = this.state === FULFILLED ? resolve : reject
        settled(this.result)
        return
      }
      // 2、回调函数是一个函数
      try {
        const data = callback(this.result)
        // 3、返回的是不是promise(满足promiseA+规范就行)
        if (this.isPromiseLike(data)) {
          data.then(resolve, reject)
        } else {
          resolve(data)
        }
      } catch (error) {
        reject(error)
      }
    })
  }

  run() {
    if (this.state === PENDING) return
    while (this.handlers.length) {
      const {
        onFulfilled,
        onRejected,
        reject,
        resolve
      } = this.handlers.shift()
      if (this.state === FULFILLED) {
        this.runOne(onFulfilled, resolve, reject)
      } else {
        this.runOne(onRejected, resolve, reject)
      }
    }
  }

  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      this.handlers.push({
        onFulfilled,
        onRejected,
        resolve,
        reject
      })
      this.run()
    })
  }
}

// 测试
function delay(duration = 1000) {
    return new MyPromise((resolve, reject) => {
      setTimeout(resolve, duration)
    })
}
async function test() {
    await delay(1000)
    console.log('ok1');
    await delay(1000)
    console.log('ok2');
}
test()

// const p = new MyPromise((resolve, reject) => {
//   setTimeout(() => {
//     resolve(1)
//   }, 1000);
// })
// p.then((data) => {
//   console.log('ok1', data);
//   return new Promise((resolve, reject) => {
//     setTimeout(() => {
//       resolve(data * 2)
//     }, 1000);
//   })
// }).then((data) => {
//   console.log('ok2', data);
// })

  

标签:resolve,const,state,promise,reject,return,手写,data
From: https://www.cnblogs.com/duanlibo/p/17393791.html

相关文章

  • 手写Promise
    //计录Promise的三种状态constPENDING="pending";constFULFILLED="fulfilled";constREJECTED="rejected";//创建微队列,把传递的函数放到微队列functionrunMicroTask(callback){ if(process&&process.nextTick){  process.nextTick(c......
  • 如何手写一个promise函数
    constPENDING='pending'constFULFILLED='fulfilled'constREJECT='rejected';classMyPromise{#state=PENDING#result=undefined#handler=[]constructor(executor){constresolve=(data)......
  • tensorflow实现mnist手写数字识别
    1.softmax函数在数学,尤其是概率论和相关领域中,归一化指数函数,或称Softmax函数,是逻辑函数的一种推广。它能将一个含任意实数的K维向量z“压缩”到另一个K维实向量σ(z)中,使得每一个元素的范围都在(0,1)之间,并且所有元素的和为1。该函数多用于多分类问题中。在多项逻辑回归和......
  • 手写分布式事务demo
    这个例子仿照seata的AT模式分布式事务产生: 其中localsql和other方法都是对当前服务数据库进行查询,但remoteMthod接口调用的远程服务库,单纯使用Spring的@Transactional注解无法回滚其他服务 ......
  • 一道Promise面试题,并对比向其代码中添加await关键字后的变化
    标准代码:(function(){console.log(1);window.setTimeout(()=>{console.log(2);},100);newPromise((resolve)=>{console.log(3);resolve();}).then(()=>{console.log(4);......
  • element-ui上传组件,before-upload发送异步请求 + Promise
    element-ui上传组件,before-upload发送异步请求+Promisebefore-upload为false的时候会阻止图片的上传但是和chenge事情一起不行可以:http-request="fnUploadRequest"<el-upload--snip--:before-upload="beforeAvatarUpload"--snip--......
  • 跟着B站手写redux
    来,跟我一起手写Redux!(建议2倍速播放)_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1dm4y1R7RK/?spm_id_from=333.788&vd_source=fdb6783d7930065bbf3d29c851463887 //src目录结构│App.jsx│index.jsx│redux.jsx│style.css│└─connectersconnectT......
  • LeetCode 周赛 344(2023/05/07)手写递归函数的固定套路
    本文已收录到AndroidFamily,技术和职场问题,请关注公众号[彭旭锐]提问。大家好,我是小彭。今天下午有力扣杯战队赛,不知道官方是不是故意调低早上周赛难度给选手们练练手。往期周赛回顾:LeetCode单周赛第343场·结合「下一个排列」的贪心构造问题周赛概览T1.找出不......
  • 第10章:10W QPS真刀实操__以及基于ZK+Netty手写分布式测试工具 177手机路人甲账号 主目
    10WQPS真刀实操__以及基于ZK+Netty手写分布式测试工具参考链接系统架构知识图谱(一张价值10w的系统架构知识图谱)https://www.processon.com/view/link/60fb9421637689719d246739秒杀系统的架构https://www.processon.com/view/link/61148c2b1e08536191d8f92f10WQPS真刀实......
  • Promise学习
    1.理解1)Promise是一门新技术(ES6规范)2)Promise是JS中进行异步编程的新解决方案 2.具体表达1)从语法上说:Promise是一个构造函数,2)从功能上说:Promise对象用来封装一个异步操作并可以获取其成功/失败的结果值支持链式调用,解决回调地狱问题,回调函数中多次嵌套。 3.Promise......