Promise的状态吸收

前景提示

没有讲解promise的一些基础,对promise还没有了解的可先看现代JavaScript教程(顺便说一下,这整套教程真的讲的很好)

先讨论一个点,then里面的回调什么时候加入到微队列中?

1. 当promise的状态变为已完成时,将所有等待队列的回调函数加入微队列
2. 执行到then时,如果promise的状态是已完成,直接将回调函数加入微队列,否则加入等待队列

代码举例说明:
这两段代码的执行结果分别是什么

new Promise((resolve, reject) => {
  resolve(2)
  new Promise((resolve, reject) => {
    resolve(5)
  }).then(res=>console.log(res))
}).then(res=>console.log(res))

new Promise(( resolve, reject ) => {
  setTimeout(() => {
    resolve(2)
    new Promise(( resolve, reject ) => {
      resolve(5)
    }).then(res => console.log(res))
  })
}).then(res => console.log(res))

第一段的结果是 5 2
第二段的结果是 2 5

  1. 对于第一段代码,resolve函数执行之后,promise的状态就为已完成,两个promise都是这样,后面执行到then时,直接将回调函数加入微队列执行
  2. 对于第二段, 当底部的then执行时, promise的状态还是pending,将回调函数加入等待队列,等定时器执行时,先执行resolve(2),此时将等待队列的回调函数加入微队列,然后再执行第二个promise

状态吸收

先看一段测试代码

const p1 = new Promise((resolve, reject)=>{
  console.log(1)
  resolve()
}).then((res)=>{
    console.log(2)
    return Promise.resolve()
}).then(()=>{
    console.log(3)
})

const p2 = new Promise((resolve, reject)=>{
  console.log(4)
  resolve()
}).then((res)=>{
    console.log(5)
}).then(()=>{
  console.log(6)
}).then(()=>{
  console.log(7)
}).then(()=>{
  console.log(8)
})

先说结果

1 4 2 5 6 7 3 8

如果大佬答对了,且知道为什么可以划走了

解释:
在状态吸收时,会经历两个过程

准备 吸收
解释不清楚,直接看下面微队列的变化

执行栈: 1 4 
微队列: 2 5
当前输出结果:
执行栈: 2 5
微队列: 准备 6
当前输出结果: 1 4
执行栈: 准备 6
微队列: 吸收 7
当前输出结果: 1 4 2 5
执行栈: 吸收 7
微队列: 3 8
当前输出结果: 1 4 2 5 6
执行栈: 3 8
微队列:当前输出结果: 1 4 2 5 6 7
执行栈:微队列:当前输出结果: 1 4 2 5 6 7 3 8

即,(res)=>{ console.log(2) return Promise.resolve() } 这个回调函数返回的是一个promise,那么then()返回的promise就会去吸收这个promise的状态,但是这个吸收不是一步就完成的,要经过准备,吸收这两个阶段

如果发现有问题,欢迎指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值