Skip to content

Add task into microtask queue

async和await的面试题【渡一教育】_哔哩哔哩_bilibili When the function after await finished, the followed code will be add to microtask queue. Remember that await doesn't not execute subsequent code immediately after the function finished.

The following two pieces of code are equivalent, both immediately adding subsequent code to the microtask queue:

js
    Promise.resolve().then(() => {
      // some code should add into micro task queue immediately
    });

    await new Promise((resolve) => {
      resolve();
    });
    // some code(include return) should add into micro task queue immediately

And, if there is no code after await, the async function finish task also will be add into microtask queue.

example:

js
  const async1 = async () => {
    console.log('1');
    Promise.resolve().then(() => {
      console.log('3'); // add this code into micro task queue
    });
  };

  const async2 = async () => {
    console.log('2');

    await new Promise((resolve) => {
      resolve();
    });

    console.log('4');
  };

  async1();
  async2();