JS async await execution process

 Example


console.log("0")

async function f() {

    console.log("1");

    const pr1 = await new Promise((resolve) => {

        console.log("2");


        setTimeout(() => {

            console.log("3");

            resolve("pr1");

        }, 5000);

    });

    const pr2 = await new Promise((resolve) => {

        console.log("4");

        setTimeout(() => {

            console.log("5");

            resolve("pr2");

        }, 2000);

    });

    return [pr1, pr2];

}

console.log("6");

f().then(result => console.log("Result:", result));

console.log("7");



==========OUTPUT==========

0

6

1

2

7

3 (after 5 seconds)

4

5 (after 2 seconds)

Result: [pr1, pr2]




Execution order

  1. console.log("0")

    0
  2. async function f() is just declared. Nothing runs yet.
  3. console.log("6")

    6
  4. f() is called.

    • console.log("1")
    • First promise is created.
    • Executor of the promise runs immediately.
    • console.log("2")
    • setTimeout(..., 5000) is scheduled.
    • Execution pauses at the first await.

    Output so far:

    0
    6
    1
    2
  5. Control returns to the caller.
  6. console.log("7")

    7
  7. After 5 seconds, the first timer fires.

    3

    The first promise resolves, so the async function resumes in a microtask.

  8. Execution continues after the first await.

    • Second promise is created.
    • Executor runs immediately.
    4
    • setTimeout(..., 2000) is scheduled.
    • Execution pauses at the second await.
  9. After 2 more seconds, the second timer fires.

    5

    The second promise resolves, so the async function resumes, returns:

    ["pr1", "pr2"]
  10. The .then() callback runs as a microtask.

    Result: [ 'pr1', 'pr2' ]

    (Exact formatting depends on the JavaScript environment.)


Comments

Popular posts from this blog

JavaScript Must-Read Topics for Senior Developer Interviews

The Evolution of Rendering in React: From Client-Side to Server Components

Scalable Websocket Systems: What to know?