js宏任务和微任务面试题

2021-01-12  本文已影响0人  A_dfa4
async function async1 () {
  console.log('async1 start');
  await async2();
  console.log('async end')
}

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

console.log('script start')

setTimeout(() => {
  console.log('serTimeout')
}, 0)

async1()

new Promise((function (resolve) {
  console.log('promise1')
  resolve()
})).then(function () {
  console.log('promise2')
}).then(function () {
  console.log('promise3')
}).then(function () {
  console.log('promise4')
})
console.log('script end')
console.log('222')
console.log(document.getElementsByTagName('body'))

// 'script start'
// 'async1 start'
// 'async2'
// 'promise1'
// 'script end'
// 'async1 end'
// 'promise2'  promise3  promise4
// "serTimeout"
// 1. 创建函数async1 创建函数async2
// 2. 执行主线程 打印 script start
// 3. 遇到setTime 放到宏任务
// 4. 执行async1 函数 打印 async1 start执行async2函数打印async2 放入微任务
// 5. 继续执行 new Promise是立即执行 打印peimise1 resolve是异步的 放到微任务
// 6. 往下执行 打印 script end 
// 7. 主线程执行完毕 看看微任务(拿出来一个执行一个就是event loop) 先打印 async end 然后再看看再执行 promise2
// 8. 微任务执行完了执行宏任务 打印 settimeout


// Event 时间队列
// 微任务和宏任务 
// 主线程 -> 微任务(async/promise/resolve/jeject) -> 宏任务(定时器/时间绑定/XJAX)
// new 函数会立即执行 new 的时候是同步的
// 查找执行的过程叫 event loop
上一篇 下一篇

猜你喜欢

热点阅读