Promise微任务例子分析--彻底理解(有基础的再看)

 console.log('*********************************************************')
        setTimeout(() => {
            console.log("主要是看宏任务什么时候执行")
        }, 0);
        var p1 = new Promise((res, rej) => {
            res('promise 1 的 then1')
        }).then(res => {
            
            console.log(res)
//  promise 1 的子promise1-2 
            new Promise((res, rej) => {
                //  setTimeout(() => {
                //     res('新的 promise')
                //  }, 1000);
                res('promise 1 的子promise1-2 的 then1')                 // 这里又给微任务队列注册了一个队列
            }).then(v => {
                console.log(v)
                return 'promise1-2 的 then2 '
            }).then(v => {
                console.log(v)
            })
            return 'prmise 1 的 then2'
        }).then(v => {
            console.log(v)
        })

        var p2 = new Promise((res, rej) => {
            res('promise 2 的 then 1')
        }).then(res => {
           
            console.log(res)
           
            return 'promise 2 的 then 2'

        }).then(v => {
            console.log(v)
        })

      

分析:

这个例子其实说明了 promise决议后 如果有then,就会把then再临时加入微任务队列末尾,继续执行

          顺序执行代码 一开始 只有promise1,promise2 完成决议判读 所以 微任务队列 只有 promise1 promise2,

执行 promise 1 的 then1 时候, 产生新的Promise1-2,并且完成决议,所以微任务队列末尾加入promise1-2 的 then1,

截至执行了 return, 此时promise1 完成决议,又把 promise 1 的 then2 加入末尾队列,

=== 》 此时只是 打印了 promise 1 的 then1,

         接着执行 微任务队列, ==》打印 promise 2 的 then 1,又把promise 2 的 then 2 加入微任务队列,

执行微任务队列里的 promise1-2 时候,==》打印 promise 1 的子promise1-2 的 then1,

又把 promise 1 的 子promise1-2 的 then2 加入微任务队列,接着打印==》 promise1的 then2 ,

       此时并不产生新的决议,所以没有新的promise加入微任务队列,接着执行 promise 2 的 then 2 打印==》promise 2 的 then 2,接着执行 promise1-2 的 then2 打印 ==》 promise1-2 的 then2

     到此时 微任务全部执行完毕i,开始执行宏认为队列,打印 ==》主要是看宏任务什么时候执行

打印顺序完整为:

       promise 1 的 then1

      promise 2 的 then 1

     promise 1 的子promise1-2 的 then1

     prmise 1 的 then2

     promise 2 的 then 2

     promise1-2 的 then2

主要是看宏任务什么时候执行

 

微任务队列 完整顺序:

promise1(promise 1 的 then1) ==》promise2( promise 2 的 then 1) ==》 promise1-2 的 then1 ==》

promise 1 的 then2 ==》 promise 2 的 then 2 ==》 promise1-2 的 then2

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值