skip to Main Content
async function async1() {
  console.log("a");
  await async2();
  console.log("b");
}

async function async2() {
  console.log("c");
  await async3();
  console.log("zzzzz");
}

const async3 = async () => {
  console.log("qqqq");
};

console.log("d");
async1();

setTimeout(() => {
  console.log("e");
}, 0);

new Promise((resolve, reject) => {
  console.log("f");
  resolve();
}).then(() => {
  console.log("g");
});
.as-console-wrapper { max-height: 100% !important; }

Here’s what I envisioned:
d, a, c, qqqq, f, zzzzz, b, g, e。

But the order in which it runs in the browser is:

d
a
c
qqqq
f
zzzzz
g
b
e

After the first execution completes, the microtask queue should be console.log("zzzzz"); console.log("b"); console.log("g");
The order of execution is, zzzzz b g, but the result in the browser is not like this, is there something I’m thinking wrong?

extremely grateful!

2

Answers


  1. After the first execution completes, the microtask queue should be console.log("zzzzz"); console.log("b"); console.log("g");

    "b" is not in the queue. The promise returned by async2 has not yet resolved.

    When synchronous code finishes, there are two promises in the resolved state: the one returned by async3, and the one created by new Promise. So the microtask queue contains 2 things: resuming async2 (ie, console.log("zzzzz")) and the anonymous .then callback (ie, console.log("g")).

    async2 resumes, logs "zzzzz", then returns (which resolves its promise). A microtask is queued up to resume async1 (ie, console.log("b")), but it must go to the end of the queue. Next the .then callback runs, logging "g". And only after that can async1 resume and log "b".

    Login or Signup to reply.
  2. console.log("d");
    
    async function async1() {
      console.log("a");
      await async2();
      console.log("b");
    }
    
    async function async2() {
      console.log("c");
      await async3();
      console.log("zzzzz");
    }
    
    const async3 = async () => {
      console.log("qqqq");
    };
    
    async1();
    
    setTimeout(() => {
      console.log("e");
    }, 0);
    
    new Promise((resolve, reject) => {
      console.log("f");
      resolve();
    }).then(() => {
      console.log("g");
    });

    Output:
    d
    a
    c
    qqqq
    zzzzz
    b
    f
    g
    e

    This sequence is based on the understanding of asynchronous behavior in JavaScript. The async/await syntax, setTimeout, and Promise callbacks contribute to the order of execution. If you have any further questions or need additional clarification, feel free to ask!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search