宏任务和微任务+超全面试真题(持续更新ing

概念

微任务和宏任务是在异步编程中经常使用的概念,用于管理任务的执行顺序和优先级。

  • 宏任务:setTimeout, setInterval,I/O 操作和 UI 渲染等。
  • 微任务: Promise 回调、async/await等

微任务通常比宏任务具有更高的优先级。

执行情况

  1. 微任务会在当前宏任务执行完毕后立即执行,而宏任务则需要等待当前宏任务执行完毕后,再从宏任务队列中选择下一个宏任务执行。
  2. 微任务(Microtask) 总是在所有的 宏任务(Macrotask) 之前执行。

当一个宏任务执行完毕后,JavaScript 引擎会立即检查微任务队列,并执行所有微任务。微任务队列为空后,引擎才会继续执行下一个宏任务。

好处:
保持状态一致性:在执行微任务时,保证了所有相关的异步操作在同一个宏任务执行周期内完成。这有助于在执行下一个宏任务之前,确保应用状态的一致性和数据的完整性。

具体执行顺序

  1. 当执行脚本开始时,会先执行一个宏任务(通常是脚本本身)。
  2. 执行完当前宏任务后,检查微任务队列。
  3. 如果微任务队列不为空,则按照先进先出的顺序依次执行所有微任务,直到微任务队列为空。这意味着微任务会在下一个宏任务之前执行。
  4. 当前宏任务执行完毕后,浏览器会渲染页面更新UI。
  5. 检查是否有新的宏任务进入事件队列。如果有,则选择最早进入队列的宏任务,并执行它。如果队列为空,则继续等待新的宏任务进入队列。
    重复步骤2-5,循环执行宏任务和微任务。

面试题

题目1

console.log('1');

setTimeout(function() {
  console.log('2');
}, 0);

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

console.log('4');

输出:1 4 3 2
首先打印了数字1和4,这是因为它们是同步任务。然后,微任务Promise的回调函数被添加到微任务队列中。接下来,通过setTimeout函数创建的定时器被添加到宏任务队列中。当JavaScript引擎处于空闲状态时,它会先执行微任务队列中的任务,然后再执行宏任务队列中的任务。

所以,数字3首先被打印,这是因为微任务具有更高的优先级,它会在当前任务完成后立即执行。然后,数字2被打印,这是因为宏任务需要等待一段时间,直到JavaScript引擎空闲时才会执行。

题目2

console.log('script start');

setTimeout(() => {
  console.log('setTimeout'); // 宏任务
}, 0);

Promise.resolve().then(() => {
  console.log('promise1'); // 微任务
}).then(() => {
  console.log('promise2'); // 微任务
});

console.log('script end');

在这里插入图片描述

题目3

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  console.log("async2");
}
console.log("script start");
async1();
console.log("script end");
// 输出顺序:
// script start
// async1 start
// async2
// script end  !!
// async1 end  !! 容易错

await async()后面的代码相当于是在.then里面执行的,所以会先执行 script end
在这里插入图片描述

题目4

console.log("Start");

    new Promise((resolve) => {
      console.log("Inside Promise");
      resolve();
    }).then(() => {
      console.log("Promise then");
    });

    console.log("End");

在这里插入图片描述

Promise 的回调(即 .then、.catch、.finally 里的函数)会被添加到微任务队列中,注意不是Promise的参数

题目5

console.log('Start');

async function asyncFunc() {
  console.log('Inside async function');
  await new Promise((resolve) => {
    console.log('Inside Promise');
    resolve();
  });
  console.log('After await');
}

asyncFunc();

console.log('End');

在这里插入图片描述

题目6

  console.log("Start");

    async function asyncFunc() {
      console.log("Inside async function");
      await new Promise((resolve) => {
        console.log("Inside Promise");
        resolve();
      }).then((res) => {
        console.log("then");// 注意这里
      });
      console.log("After await");
    }

    asyncFunc();

    console.log("End");

+

题目7

初创外企的面试题

 const printing = () => {
    console.log('A');
    setTimeout(() => { console.log('B'); }, 1000);
    setTimeout(() => { console.log('C'); }, 0);
    console.log('D');
    console.log('E');
    }

    printing();

A D E C B

题目8

 console.log(1);  // 
 
    setTimeout(() => {
      console.log(2);  //
    });

    const p1 = new Promise((reslove) => {
      console.log(3); //
      reslove();
    });

    p1.then(() => {
      console.log(4); //
    });

    console.log(5); //

    const p2 = new Promise((reslove) => {
      console.log(6);  //
      reslove();
    });

    p2.then(() => {
      console.log(7);  //
    });

    // 1 3 5 6 4 7 2

注意setTime是宏任务,所以排到后面了

题目9

    function testAsy(x) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(x);
        }, 3000);
      });
    }
    async function testAwt() {
      let result = await testAsy("hello world");
      console.log(result); // 3秒钟之后出现hello world
      console.log("cuger"); // 3秒钟之后出现cug
    }
    testAwt();
    console.log("cug"); //立即输出cug

题目10

   console.log("script start");
    let promise1 = new Promise(function (resolve) {
      console.log("promise1");
      resolve("resolve!"); // 注意这里
      console.log("promise1 end");
    }).then(function (res) {
      console.log("promise2");
      console.log(res); // 注意这里
    });
    setTimeout(function () {
      console.log("settimeout");
    });
    console.log("script end");

在这里插入图片描述

题目11

    console.log("start");

    setTimeout(() => {
      console.log("1");

      new Promise((resolve) => {
        console.log("2");

        resolve();
      }).then(() => {
        console.log("3");
      });

      new Promise((ressolve, reject) => {
        console.log("middle");
        reject();
      })
        .then(() => {
          console.log(4);  // 注意这里!!
        })
        .catch(() => {
          console.log("5");
          setTimeout(() => {
            console.log("6");
          });
        });
    });

    console.log("end");

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值