事件循环机制-面试题


执行顺序:整个脚本-->异步任务
异步任务 分为宏任务和微任务,先执行微任务再执行宏任务

  • 宏任务:script 、setTimeout、setInterval 、setImmediate 、I/O 、UI rendering
  • 微任务:MutationObserver、Promise.then()或reject()

注意:遇到async函数的时候,await之后的代码属于微任务,相当于promise.then
其中,new Promise为立即执行函数。接下来看几个例子

async function a() {
    console.log('a')
    await b()
    console.log('a end')
}

async function b() {
    console.log('b')
}

a()

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

new Promise(function (resolve, reject) {
    console.log('promise')
    resolve()
}).then(function () {
    console.log('then')
})

console.log('main end')

// a
// b
// promise
// main end
// a end
// then
// setTimeout
setTimeout(function () {
  console.log('8')
}, 0) 
async function async1() {
  console.log('1')
  const data = await async2()
  console.log('6')
  return data
}
async function async2() {
   return new Promise(resolve => {
    console.log('2')
    resolve('async2的结果')
  }).then(data => {
    console.log('4')
    return data
  })
}
async1().then(data => {
  console.log('7')
  console.log(data)
})
new Promise(function (resolve) {
  console.log('3')
  resolve()
}).then(function () {
  console.log('5')
})

// 1 2 3 4 5 6 7 async的结果 8


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM