跟我一起来刷题(3)——JS单线程执行顺序

215 阅读1分钟

考查知识点

  • 理解JS是一门单线程语言;
  • 理解宏任务和微任务相关;

微任务队列

  • promise
  • MutationObserver
  • process.nexTick
  • async;await

宏任务队列

  • setTimeout
  • setInterval
  • UI rending
  • script

第一题

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

第二题

async function async1() {
    console.log( 'async1 start' )
    await async2()
    console.log( 'async1 end' )
}
async function async2() {
    console.log( 'async2' )
}
console.log( 'script start' )
setTimeout( function () {
    console.log( 'setTimeout' )
}, 0 )
async1();
new Promise( function ( resolve ) {
    console.log( 'promise1' )
    resolve();
} ).then( function () {
    console.log( 'promise2' )
} )
console.log( 'script end' )

执行结果:

  • script start
  • async1 start
  • async2 promise1
  • script end
  • async1 end
  • promise2
  • setTimeout