封装Promise

该文章展示了如何使用JavaScript实现一个Promise对象,包括构造函数、状态管理(pending,fulfilled,rejected)、then方法处理成功与失败的回调,以及在异步操作完成后调用相应的回调函数。通过实例演示了Promise的用法,如setTimeout模拟异步操作。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    class PromiseA {
      constructor(executor) {
        this.state = 'pending' //初始化state为等待装态
        this.value = undefined //记录成功的状态值  将来的 .then使用
        this.reason = undefined //记录失败的状态值  将来的 .catch使用


        this.onResolvedCallback=[]//存放当成功时,需要执行的函数
        this.onRejectedCallback=[]//存放当失败时,需要执行的函数


        let resolve = (value) => {
          //只有我们的pending状态能被改变其他不能
          if (this.state == 'pending') {
            // console.log('将状态改成成功,记录成功的信息');
            this.state = 'fulfilled' //更新装态
            this.value = value
            //立刻调用成功的数组函数
            this.onResolvedCallback.forEach(fn=>fn())
          }
        }

        let reject = (reason) => {
          if (this.state == 'pending') {
            // console.log('将状态改成失败,记录失败的信息');
            this.state = 'rejected' //更新装态
            this.reason = reason
            //立刻调用失败的数组函数
            this.onRejectedCallback(fn=>fn())
          }
        }

        //如果执行executor报错,直接reject
       try{
        executor(resolve, reject)
       }catch(err){
        reject(err)
       }
      }
      then(onFulFilled,onRejected){
        //onFulFilled 如果成功了,应该调用
        if(this.state=='fulfilled'){
          onFulFilled(this.value)
        }
        //onRejected 如果失败了,应该调用
        if(this.state=='rejected'){
          onRejected(this.reason)
        }
        //当我们的状态为pending的时候
        if(this.state==='pending'){
          //将成功的时候要干的事,存起来
          this.onResolvedCallback.push(()=>{
            onFulFilled(this.value)
          })
          //将失败要的时候要干的事,存起来
          this.onRejectedCallback.push(()=>{
            onFulFilled(this.reason)
          })
        }
      }
    }

    //promiseA+ executor
    const p = new PromiseA((resolve, reject) => {
      setTimeout(()=>{
        resolve(200)
      },1000)
    })
    
    //这里的回调在promise更新成fulfilled
    //如果有异步,有可能不是立即满足条件,就应该等满足条件,再来执行这个函数
    p.then(res=>{
      console.log(res,'1');
    })
    p.then(res=>{
      console.log(res,'2');
    })
    p.then(res=>{
      console.log(res,'3');
    })

    //调用三次,then后,效果=>数组存了三个等待执行的函数

    // 应该在resolve,一旦resolve执行,就调用成功数组的函数
    // 应该在reject,一旦reject执行,就调用失败数组的函数
  </script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值