2022-12-31 Promise源码实现

1.实现一个简单的 promise
new Promise((resolve, reject) => {
   
    setTimeout(() => {
   
        resolve(1);
    }, 1000);
}).then(res => {
   
    console.log(res);
    return 2;
}, err = {
   }).then(res => {
   
    console.log(res);
}, err => {
   });

为了实现上述功能,从构造函数的角度,我们首先要实现一个 Promise 的类,这个类的构造函数会传入一个函数作为参数,并且向该函数传入 resolve 和 reject 两个方法。初始化 Promise 的状态为 pending。

2.实现一个Promise类
class MyPromise {
   
  constructor(executor) {
   
    this.executor = executor
    this.value = null
    this.status = 'pending'

    const resolve = value => {
   
      if (this.status === 'pending') {
   
        this.value = value          // 调用 resolve 后记录 resolve 的值
        this.status = 'fulfilled'   // 调用 resolve 扭转 promise 状态
      }
    }

    const reject = value => {
   
      if (this.status === 'pending') {
   
        this.value = value          // 调用 reject 后记录 reject 的值
        this.status = 'rejected'    // 调用 reject 扭转 promise 状态
      }
    }

    this.executor(resolve, reject)
  }

现在已经实现了这个Promise类,还要实现Promise的then方法,
then 方法会传入两个函数作为参数,分别作为 promise 对象 resolve 和 reject 的处理函数。
then 方法有以下特点:

1.then 函数需要返回一个新的 promise 对象
2.执行 then 函数的时候,这个 promise 的状态可能还没有被扭转为 fulfilled 或 rejected
3.一个 promise 对象可以同时多次调用 then 函数
3.实现then方法
class MyPromise {
   
  constructor(executor) {
   
    this.executor = executor
    this.value = null
    this.status = 'pending'
    this.onFulfilledFunctions = [] // 存放这个 promise 注册的 then 函数中传的第一个函数参数
    this.onRejectedFunctions = [] // 存放这个 promise 注册的 then 函数中传的第二个函数参数
    const resolve = value => {
   
      if (this.status === 'pending') {
   
        this.value = value
        this.status = 'fulfilled'
        this.onFulfilledFunctions.forEach(onFulfilled => {
   
          onFulfilled() // 将 onFulfilledFunctions 中的函数拿出来执行
        })
      }
    }
    const reject = value => {
   
      if (this.status === 'pending') {
   
        this.value = value
        this.status = 'rejected'
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端OnTheRun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值