宏任务 微任务 陷阱

console.log('script start')

async function async1() {
  await async2()
  console.log('async1 end')
}
async function async2() {
  console.log('async2 end')
}
async1()

setTimeout(function() {
  console.log('setTimeout')
}, 0)

new Promise(resolve => {
  console.log('Promise')
  resolve()
})
  .then(function() {
    console.log('promise1')
  })
  .then(function() {
    console.log('promise2')
  })

console.log('script end')


script start  同步代码
async2 end    
Promise
script end
async1 end
promise1
promise2
setTimeout
console.log('script start')    立即执行 1

async function async1() {
  await async2()
  console.log('async1 end')  异步队列 1 微任务
}
async function async2() {
  await console.log('async2 end')   立即执行 2
}
async1()

setTimeout(function() {
  console.log('setTimeout')   异步队列 1 宏任务
}, 0)

new Promise(resolve => {
  console.log('Promise')     立即执行  3
  resolve()
})
  .then(function() {
    console.log('promise1')  异步队列 1 微任务 
  })
  .then(function() {
    console.log('promise2')  
  })

console.log('script end')  立即执行  4

script start
async2 end
Promise
script end
promise1
async1 end
promise2
setTimeout
new Promise((r,j) => {
  r();
}).then(() => {
  console.log(1);
  Promise.resolve().then(() => {
    console.log(3)
    Promise.resolve().then(() => {
      console.log(4)
      Promise.resolve().then(() => {
        console.log(5)
      })
    })
  })
}).then(() => {
  console.log(2);
})

// 1 3 2 4 5
Promise.resolve().then(() => {
  console.log('promise1');
  const timer2 = setTimeout(() => {
    console.log('timer2')
  }, 0)
});
const timer1 = setTimeout(() => {
  console.log('timer1')
  Promise.resolve().then(() => {
    console.log('promise2')
  })
}, 0)
console.log('start');


//  start  promise1  timer1  promise2  timer2、

最大宏任务 script 
之后 Promise 异步微任务 Promise.then  script宏任务下的微任务队列
之后 setTimeout 异步宏任务 setTimeout  script宏任务下的宏任务任务队列

Promise.then 下有 setTimeout宏任务
setTimeout 下有 Promise.then 微任务

依照先执行 宏任务下的所有微任务,之后执行下一个宏任务 即
script 
Promise.then 
timer1 
timer1>Promise.resolve
timer2

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值