JavaScript 同步异步(微任务、宏任务)代码执行顺序 - 2

# 此题坑在与:await后面创建一个异步微任务,
只有等到await后面的promise实例的状态是fulfilled成功之后,await后面创建的异步微任务代码才可以执行,不然就阻塞无法执行,
本题awaitnew Promise实例的状态一直是pending状态的,
所以 console.log('async1 end'); return 'async1 success'无法执行到这里。

const async1 = async () => {
  console.log('async1');
  setTimeout(() => {
    console.log('timer1')
  }, 2000)
   await new Promise(resolve => { # promise的状态是pending的
    console.log('promise1')
  })
  console.log('async1 end')
  return 'async1 success'
}
console.log('script start');

async1().then(res => console.log(res)); // promise的状态不是成功执行不到then中
console.log('script end');

Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .catch(4)
  .then(res => console.log(res)) // 穿透了

setTimeout(() => {
  console.log('timer2')
}, 1000)
'script start'
'async1'
'promise1'
'script end'
1
'timer2'
'timer1'

# 改版1
const async1 = async () => {
  console.log('async1');
  setTimeout(() => {
    console.log('timer1')
  }, 2000)
   await new Promise(resolve => {
    console.log('promise1')
    resolve() // 新加
  })
  console.log('async1 end')
  return 'async1 success'
}
console.log('script start');
async1().then(res => console.log(res));
console.log('script end');
Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .catch(4)
  .then(res => console.log(res))
setTimeout(() => {
  console.log('timer2')
}, 1000)

script start
async1
promise1
script end
async1 end
async1 success
1
timer2
timer1

# 改版2
const async1 = async () => {
  console.log('async1');
  setTimeout(() => {
    console.log('timer1')
  }, 2000)
  new Promise(resolve => { // 去掉await
    console.log('promise1')
    resolve()
  })
  console.log('async1 end')
  return 'async1 success'
}
console.log('script start');
async1().then(res => console.log(res));
console.log('script end');
Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .catch(4)
  .then(res => console.log(res))
setTimeout(() => {
  console.log('timer2')
}, 1000)

script start
async1
promise1
async1 end
script end
async1 success
1
timer2
timer1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值