首页 > 其他分享 >手写promise

手写promise

时间:2022-10-18 16:36:03浏览次数:44  
标签:status resolve onFulfilled myPromise promise result reject 手写

分析

对于promise的复现,我们得先考虑promise的使用。

  • 使用时可以进行new操作,那么可以用构造函数获取class来构建
  • 存在then方法
  • 可以调用resolve和reject方法
  • 有三种状态 pending、fulfilled、rejected
  • ……
class myPromise {
  static PENDING = 'pending';
  static FULFILLED = 'fulfilled';
  static REJECTED = 'rejected'
  constructor(func) {
    this.status = myPromise.PENDING
    this.result = null
    this.resovleCallbacks = []
    this.rejectCallbacks = []
    try {
      func(this.resolve.bind(this), this.reject.bind(this))
    }
    catch (error) {
      this.reject(error)
    }
  }
  resolve (result) {
    setTimeout(() => {
      if (this.status === myPromise.PENDING) {
        this.status = myPromise.FULFILLED
        this.result = result
        this.resovleCallbacks.forEach(fn => fn(result))
      }
    })
  }
  reject (result) {
    setTimeout(() => {
      if (this.status === myPromise.PENDING) {
        this.status = myPromise.REJECTED
        this.result = result
        this.rejectCallbacks.forEach(fn => fn(result))
      }
    })
  }
  then (onFulfilled, onRejected) {
    return new myPromise((resolve, reject) => {
      // then里面传递的两个参数必须为函数
      onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : () => { }
      onRejected = typeof onRejected === 'function' ? onRejected : () => { }
      if (this.status === myPromise.PENDING) {
        this.resovleCallbacks.push(onFulfilled)
        this.rejectCallbacks.push(onRejected)
      }
      if (this.status === myPromise.FULFILLED) {
        setTimeout(() => {
          onFulfilled(this.result)
        })
      }
      if (this.status === myPromise.REJECTED) {
        setTimeout(() => {
          onRejected(this.result)
        })
      }
    })

  }
}

let p = new myPromise((resolve, reject) => {
  resolve('成功了')
  // reject('失败了')
  // throw new Error('失败了')
})
p.then(res => {
  console.log('第一次执行')
})
  .then(res => {
    console.log('第二次执行', res)
  })

标签:status,resolve,onFulfilled,myPromise,promise,result,reject,手写
From: https://www.cnblogs.com/zx529/p/16803027.html

相关文章

  • axios : Promise based HTTP client for the browser and node.js
    axiosPromisebasedHTTPclientforthebrowserandnode.jsFeaturesMake​​XMLHttpRequests​​fromthebrowserMake​​http​​requestsfromnode.jsSupportsthe......
  • Promise 捕获程序中的失败
    代码varA=newPromise(function(resolve,reject){console.log('dosth.');setTimeout(()=>{console.log('~~~~~');resolve('ok');//reject......
  • Promise 只处理成功回调
    只处理成功varA=newPromise(function(resolve,reject){console.log('dosth.');setTimeout(()=>{console.log('~~~~~');resolve('ok');rej......
  • 自己动手写乞丐版线程池
    自己动手写乞丐版线程池前言在上篇文章线程池的前世今生当中我们介绍了实现线程池的原理,在这篇文章当中我们主要介绍实现一个非常简易版的线程池,深入的去理解其中的原理,......
  • 手写编程语言-如何为 GScript 编写标准库
    版本更新最近GScript更新了v0.0.11版本,重点更新了:Docker运行环境新增了byte原始类型新增了一些字符串标准库Strings/StringBuilder数组切片语法:int[]b=a......
  • 第二季:5公平锁/非公平锁/可重入锁/递归锁/自旋锁谈谈你的理解?请手写一个自旋锁【Java
    第二季:5值传递和引用传递【Java面试题】​​前言​​​​推荐​​​​值传递​​​​说明​​​​题目​​​​24TransferValue醒脑小练习​​​​第二季:5公平锁/非公平锁/......
  • 10个常见的前端手写功能,你全都会吗?
    万丈高楼平地起,地基打的牢,才能永远立于不败之地。今天给大家带来的是10个常见的JavaScript手写功能,重要的地方已添加注释。有的是借鉴别人的,有的是自己写的,如有不正确的地......
  • JS中的promise()方法
    promise的产生的由来引入概念:回调地狱像下方这种在ajax中需要再次发送ajax的需求,就会产生回调地狱     $.ajax({           url:......
  • 使用Object.defineProperty手写一个简单的双向绑定
    什么是双向绑定?1.当一个对象(变量)的属性改变,那么调用这个属性的地方显示也发生变化,模型到视图(model=>view)2.当调用属性的这个地方改变了这个属性(通常是一个表单元素),那么......
  • 手写 call 方法
    手写一个call函数call()方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法。举个栗子:varfoo={value:1};functionbar(){......