JS执行顺序的面试题(自改)

66 阅读1分钟
//网上看到的面试题,自己改版一下,不知道理解对不对,记录一下

async function async1 () {
  console.log('async1 start') // 2
  await  new Promise(resolve => {  //await右边代码同步执行,遇到promise会堵塞后面代码,异步变同步
    setTimeout(() => {
  console.log('async2')  // 6
        resolve();    
    }, 0)
})                                 //await后面代码相当于then()里的回调,参数为resolve()里的实参
  console.log('async1 end') // 7   //代码堵塞,同步先走,定时器执行完调用resolve,才走then()
}
 
console.log('script start')   // 1
 
setTimeout(function () {
  console.log('setTimeout')   // 5
}, 0)
 
async1();
 
new Promise (function (resolve) {
  setTimeout(function () {   
    console.log('promise1')  // 8
  }, 0)
  resolve(); 
}).then (function () {
  console.log('promise2')  // 4  //resolve在外面,promise2异步微任务存进队列
})
 
console.log('script end')  // 3


//其他执行顺序基本是按先同后异,先微后宏,先进先出的规律
//如果定时器有时间参数的话,按时间快慢执行

上面打印结果如下:
script start
async1 start
script end
promise2
setTimeout
async2
async1 end
promise1