带你充分了解宏任务与微任务 [ 面试题 ]

什么是宏任务与微任务

JavaScript 把异步任务又做了进一步的划分,异步任务又分为两类,分别是:
宏任务
  • 异步Ajax请求
  • setTimeout , setInterval
  • 文件操作
  • 其他宏任务
微任务
  • Promise.then , .catch 和 .finally
  • process.nextTick
  • 其他微任务
宏任务与微任务的执行顺序

 每一个宏任务执行完之后 , 都会检查是否存在待机执行的微任务 , 如果有 , 则执行完所以微任务之后 , 在继续执行下一个宏任务

setTimeout(function () {
   console.log('1');
})

new Promise(function (resolve) {
   console.log('2');
   resolve()
}).then(function () {
   console.log('3');
})

console.log('4');

 正确输出的顺序是:2431

分析:

  • 先执行所以的同步任务
  • 在执行微任务 (2 , 4)
  • 在执行下一个宏任务 (3)
  • 执行第二行代码

经典面试题 

console.log('1');
setTimeout(function () {
    console.log('2');
    new Promise(function (resolve) {
        console.log('3');
        resolve()
    }).then(function () {
        console.log('4');
    })
})
new Promise(function (resolve) {
    console.log('5');
    resolve()
}).then(function () {
    console.log('6');
})
setTimeout(function () {
    console.log('7');
    new Promise(function (resolve) {
        console.log('8');
        resolve()
    }).then(function () {
        console.log('9');
    })
})

正确的输出顺序是: 156234789

猜你喜欢

转载自blog.csdn.net/weixin_59769148/article/details/120815157