事件循環機制-面試題


執行順序:整個腳本-->異步任務
異步任務 分為宏任務和微任務,先執行微任務再執行宏任務

  • 宏任務: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