Back to series
· 12 min read

Async/Await: Modern Syntax for Asynchronous Programming


1. What Are Async / Await

Async / Await is a common asynchronous programming syntax found in modern programming languages, used to simplify the writing and organization of asynchronous tasks.

It is not a standalone asynchronous execution mechanism, but rather a language feature built on top of abstractions such as Promise, Future, or other asynchronous computations.

In JavaScript:

  • async is used to declare an asynchronous function.
  • await is used to wait for the result of a Promise or thenable.
  • An async function always returns a Promise.
  • await does not block the entire JavaScript thread; it pauses the subsequent execution of the current async function.

For example:

async function getUser() {
    return {
        id: 1,
        name: "Alice"
    };
}

async function main() {
    const user = await getUser();
    console.log(user);
}

main();

Although getUser() returns a plain object, because the function is declared async, JavaScript wraps the return value into a successfully fulfilled Promise.

It can be understood as:

function getUser() {
    return Promise.resolve({
        id: 1,
        name: "Alice"
    });
}

The two are equivalent in terms of basic result semantics, but that does not mean every detail can simply be handled by textual substitution.

1. The Role of Async

async is used to declare an asynchronous function.

async function calculate() {
    return 100;
}

Calling it:

const result = calculate();

console.log(result);

What you get is a Promise, not the number 100 directly.

Retrieving the result via then:

calculate().then(value => {
    console.log(value);
});

Output:

100

Async functions have two important characteristics:

  1. The function's return value is converted into the fulfillment result of a Promise.
  2. An exception thrown inside the function causes the returned Promise to settle in a rejected state.

For example:

async function getValue() {
    throw new Error("执行失败");
}

getValue().catch(error => {
    console.error(error.message);
});

2. The Role of Await

await is used to wait for an asynchronous result.

async function main() {
    const result = await Promise.resolve(100);

    console.log(result);
}

main();

When execution reaches await:

  • If the awaited Promise has already settled, the function continues running in a subsequent asynchronous execution phase.
  • If the Promise has not yet settled, the current async function pauses its subsequent execution.
  • The JavaScript execution environment can continue processing other tasks.
  • Once the Promise settles, the async function resumes from the point where it paused.

Note that await can wait not only for Promises but also accepts ordinary values. Ordinary values are treated as an already successfully fulfilled result.

3. The Core Value of Async / Await

Design Goal Description
Simplify asynchronous code Reduce nested Promise chains
Improve readability Make task dependencies closer to synchronous code
Unify exception handling Use try...catch to handle asynchronous failures
Simplify control flow Support conditionals, loops, and early returns
Make task composition easier Work together with Promise composition APIs

2. Why Async / Await Is Needed

Before Async / Await appeared, JavaScript already had two common approaches to asynchronous programming: callback functions and Promises.

What Async / Await primarily solves is the problem of organizing asynchronous code and expressing control flow.

1. The Callback Function Approach

Suppose three tasks need to be completed in sequence:

  1. Query the user.
  2. Query the user's orders.
  3. Query the order details.

Using callback functions:

getUser(userId, (user) => {
    getOrders(user.id, (orders) => {
        getOrderDetail(orders[0].id, (detail) => {
            console.log(detail);
        });
    });
});

This approach easily leads to callback hell.

Main problems:

  • Nesting levels are too deep.
  • Error handling is scattered.
  • Task dependencies are not intuitive.
  • Code is hard to maintain.

2. Promise Chaining

Using Promises can improve the nested structure:

getUser(userId)
    .then(user => getOrders(user.id))
    .then(orders => getOrderDetail(orders[0].id))
    .then(detail => {
        console.log(detail);
    })
    .catch(error => {
        console.error(error);
    });

Promises establish dependencies between asynchronous tasks through then.

But when the business logic involves complex conditions, loops, exception recovery, and multi-layer task composition, chained structures can still become hard to read.

3. Async / Await Approach

Using Async / Await:

async function main() {
    try {
        const user = await getUser(userId);
        const orders = await getOrders(user.id);
        const detail = await getOrderDetail(orders[0].id);

        console.log(detail);
    } catch (error) {
        console.error(error);
    }
}

The code structure is much closer to synchronous programming.

Comparison Aspect Callbacks Promise Async / Await
Code organization Nested calls Chained calls Sequential style
Error handling Callback conventions catch try...catch
Conditional branching Prone to nesting Can be achieved Close to synchronous code
Loop handling Requires extra structuring Requires composition Loops can be used directly
Combining multiple tasks Manual control Promise API await with Promise API
Underlying mechanism Function calls Promise Syntactic abstraction built on Promise

Async / Await does not replace Promise; it makes Promise more natural to use.


III. How Async Works

To understand Async / Await, you first need to understand the return value and execution semantics of async functions.

1. Async Functions Always Return a Promise

An ordinary function:

function getNumber() {
    return 100;
}

Calling it:

const result = getNumber();

console.log(result);

Yields:

100

An async function:

async function getNumber() {
    return 100;
}

Calling it:

const result = getNumber();

console.log(result);

What you get is a Promise.

You can obtain the result in the following way:

getNumber().then(value => {
    console.log(value);
});

2. How Return Values Are Wrapped

The return value of an async function is handled according to the Promise resolution process.

An ordinary value:

async function getValue() {
    return 100;
}

is equivalent to returning a successfully fulfilled Promise.

Returning a Promise:

async function getValue() {
    return Promise.resolve(100);
}

The async function adopts the final state and result of the returned Promise, rather than nesting it directly as an ordinary object.

For example:

async function getValue() {
    return Promise.resolve(100);
}

getValue().then(value => {
    console.log(value);
});

Output:

100

3. Exception Handling in Async Functions

Exceptions thrown inside an Async function are converted into the rejection state of the returned Promise.

async function calculate() {
    throw new Error("计算失败");
}

calculate().catch(error => {
    console.error(error.message);
});

You can also use try...catch to handle it inside the function:

async function calculate() {
    try {
        throw new Error("计算失败");
    } catch (error) {
        console.error(error.message);
    }
}

Here the exception has already been caught and the function ends normally, so the returned Promise will fulfill successfully, with undefined as its result.

4. Async Function Execution Flow

flowchart TD
    A["Call Async Function"] --> B["Create Returned Promise"]
    B --> C["Execute Synchronous Part of Function Body"]
    C --> D{"Encounter await?"}
    D -->|"No"| E["Continue Executing Function Body"]
    D -->|"Yes"| F["Wait for Asynchronous Result"]
    F --> G["Pause Subsequent Execution of Current Function"]
    G --> H["Wait for Result Completion"]
    H --> I{"Execution Result"}
    I -->|"Success"| J["Resume Function Execution"]
    I -->|"Failure"| K["Throw Rejection Reason"]
    J --> D
    K --> L["Exception Handling or Promise Rejection"]
    E --> M["Function Returns Normally"]
    M --> N["Promise Completes Successfully"]
    L --> O["Promise Completes with Failure"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style M fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style N fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style O fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

IV. Await Execution Mechanism

await is the most critical syntax in Async / Await.

Its core function is to pause the subsequent execution of the current async function and resume execution after the awaited object completes.

1. Await Waits for a Promise

async function main() {
    console.log("开始");

    const result = await new Promise(resolve => {
        setTimeout(() => {
            resolve(100);
        }, 1000);
    });

    console.log("结果:", result);
    console.log("结束");
}

main();

Output:

开始
结果:100
结束

During execution, await does not block the entire JavaScript main thread.

It only pauses the part of the current async function that comes after await.

While waiting, the JavaScript runtime can continue handling other tasks.

2. Awaiting a Plain Value

await does not require its operand to be a Promise.

async function main() {
    const a = await 100;
    const b = await "hello";

    console.log(a);
    console.log(b);
}

main();

A plain value is treated as an already successfully settled result.

However, even when awaiting a plain value, the code after await still resumes asynchronously.

For example:

console.log("A");

async function main() {
    console.log("B");

    await 100;

    console.log("C");
}

main();

console.log("D");

Output:

A
B
D
C

The reason is:

  • When main() is called, the code before await runs synchronously.
  • Upon reaching await, the current async function pauses.
  • The main thread continues executing the subsequent synchronous code.
  • Once the current call stack is cleared, the async function resumes.

3. Awaiting a Thenable

Besides Promises, await can also wait for objects that have a then method — that is, thenables.

const thenable = {
    then(resolve) {
        resolve(100);
    }
};

async function main() {
    const result = await thenable;
    console.log(result);
}

main();

JavaScript handles a thenable according to the Promise resolution procedure.

This allows await to work with asynchronous result objects other than Promises.

4. Await's Resume Mechanism

flowchart TD
    A["Execute the Async Function"] --> B["Run the code before await"]
    B --> C["Encounter the await expression"]
    C --> D["Process the awaited object"]
    D --> E["Pause the current Async function"]
    E --> F["Wait for the Promise or thenable to settle"]
    F --> G{"Wait for the result"}
    G -->|"Success"| H["Resume and obtain the result"]
    G -->|"Failure"| I["Resume and throw an exception"]
    H --> J["Continue with the following code"]
    I --> K["Enter exception handling"]
    J --> L["The function continues or returns"]
    K --> L

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style I fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

V. Async / Await and the Event Loop

In JavaScript, Async / Await is tightly tied to the microtask scheduling mechanism of Promises.

Only by understanding the event loop can you accurately determine the execution order of asynchronous code.

1. The Code After Await Belongs to the Asynchronous Resume Process

For example:

console.log("1");

async function main() {
    console.log("2");

    await Promise.resolve();

    console.log("3");
}

main();

console.log("4");

Output:

1
2
4
3

Analysis:

  1. Output 1.
  2. main() is called, outputting 2.
  3. Execution reaches await, and the current function is suspended.
  4. Synchronous code continues to run, outputting 4.
  5. The current call stack is emptied.
  6. main() resumes, outputting 3.

2. The Relationship Between Await and Promise.then

The following two forms are similar in their basic execution order:

async function main() {
    const result = await Promise.resolve(100);
    console.log(result);
}
function main() {
    return Promise.resolve(100).then(result => {
        console.log(result);
    });
}

Both of them make use of Promise's asynchronous result-handling mechanism.

But Async / Await also involves language-level semantics such as function suspension and resumption, preservation of the lexical environment, and exception conversion, so it cannot simply be regarded as a textual replacement for then.

3. Microtask Execution Order

console.log("A");

async function main() {
    console.log("B");

    await Promise.resolve();

    console.log("C");
}

main();

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

console.log("E");

Output:

A
B
E
C
D

Reasons:

  • When main() reaches await, it schedules a microtask to resume execution.
  • The then callback registered afterward enters the microtask queue.
  • The synchronous code outputs E first.
  • The resume task registered earlier runs first, outputting C.
  • The Promise callback registered later then outputs D.

4. The Relationship Between Await and the Event Loop

flowchart TD
    A["Start executing the current task"] --> B["Execute synchronous code"]
    B --> C["Call the async function"]
    C --> D["Execute code before await"]
    D --> E["Encounter await"]
    E --> F["Schedule resumption of execution"]
    F --> G["Continue executing other synchronous code"]
    G --> H["Current task ends"]
    H --> I["Execute the microtask queue"]
    I --> J["Resume the async function"]
    J --> K["Execute code after await"]
    K --> L["Enter the next event loop phase"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note:

What is described here is the common event loop execution model of JavaScript. Browsers and Node.js differ in task sources, phase scheduling, and specific runtime behavior, so this simplified model should not be taken as a complete scheduling specification for all environments.


VI. Exception Handling in Async / Await

Exception handling in asynchronous tasks is one of the important advantages of Async / Await.

Traditional Promise chains handle failures through catch, while Async / Await can use the familiar try...catch.

1. Using try...catch

async function getData() {
    throw new Error("数据获取失败");
}

async function main() {
    try {
        const result = await getData();
        console.log(result);
    } catch (error) {
        console.error(error.message);
    }
}

main();

When the Promise returned by getData() is rejected, await re-represents the rejection reason as an exception in the current async function.

Therefore, you can use the familiar exception-handling structure from synchronous code.

2. Using finally to Clean Up Resources

async function loadData() {
    try {
        const result = await fetch("/api/data");

        return await result.json();
    } catch (error) {
        console.error("请求失败", error);
        throw error;
    } finally {
        console.log("请求处理结束");
    }
}

finally is suitable for cleanup work that must be performed regardless of success or failure, for example:

  • Turn off the loading state.
  • Release temporary resources.
  • Clean up temporary state.
  • Record execution time.

Note: A return in finally may override the value originally intended to be returned in try or catch; this should usually be avoided in exception-handling logic.

3. Error Propagation

If an async function does not catch an internal exception, the Promise it returns will complete in a rejected state.

async function getUser() {
    throw new Error("用户不存在");
}

async function main() {
    const user = await getUser();
    console.log(user);
}

main().catch(error => {
    console.error(error.message);
});

Here the exception propagates from getUser to main and is ultimately handled by the caller's catch.

4. Exception Handling Flow

flowchart TD
    A["Call Async function"] --> B["Execute await"]
    B --> C{"Async task result"}
    C -->|"Success"| D["Return result"]
    C -->|"Failure"| E["Throw exception"]
    D --> F["Continue execution"]
    E --> G{"Does try...catch exist?"}
    G -->|"Yes"| H["Execute catch"]
    G -->|"No"| I["Async function returns rejected Promise"]
    H --> J{"Resume execution?"}
    J -->|"Yes"| K["Continue subsequent logic"]
    J -->|"No"| L["Propagate exception outward"]
    I --> M["Caller handles rejection"]
    L --> M
    F --> N["Function completes"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style M fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style N fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

5. Common Exception Handling Pitfalls

Pitfall 1: Asynchronous calls without await will also be caught by try...catch.

async function main() {
    try {
        getData();
    } catch (error) {
        console.error(error);
    }
}

If getData() returns a rejected Promise, but there is no await or other rejection handling mechanism, the try...catch here cannot catch that asynchronous rejection.

It should be written as:

async function main() {
    try {
        await getData();
    } catch (error) {
        console.error(error);
    }
}

Pitfall 2: After catch handles an exception, the exception will definitely continue to propagate outward.

Not necessarily.

If catch does not rethrow the exception, the current async function will usually continue executing and may return successfully.

Pitfall 3: All asynchronous exceptions can be caught by the outermost try...catch.

Incorrect.

Whether an exception can be caught depends on whether it occurs in the corresponding synchronous call stack or is propagated through a Promise rejection chain.


7. Sequential and Concurrent Execution of Async / Await

Async / Await code often looks like synchronous code, but you should not assume that tasks run concurrently just because await is used.

This is one of the most common performance issues in real-world development.

1. Sequential Execution

async function main() {
    const user = await getUser();
    const orders = await getOrders();
    const config = await getConfig();

    return { user, orders, config };
}

Here the three tasks execute one after another.

If each task takes 1 second, the total time may be close to 3 seconds.

Applicable scenarios:

  • Subsequent tasks depend on previous results.
  • Operations must be executed in business order.
  • There are state updates or transaction dependencies.

2. Concurrent Execution

If tasks are independent of each other, you can create the Promises in advance and then await them together.

async function main() {
    const userPromise = getUser();
    const ordersPromise = getOrders();
    const configPromise = getConfig();

    const [user, orders, config] = await Promise.all([
        userPromise,
        ordersPromise,
        configPromise
    ]);

    return { user, orders, config };
}

Here, the three asynchronous tasks can start at the same time, and the overall wait time is usually close to the completion time of the slowest task rather than the sum of the three tasks' durations.

Note: This is concurrent organization; it does not mean multiple threads are necessarily used or that CPU parallelism is achieved.

3. Comparison of Sequential and Concurrent Execution

Comparison Dimension Sequential Execution Concurrent Execution
Task startup Start sequentially Start as early as possible
Dependencies between results Suitable for dependent tasks Suitable for independent tasks
Total duration Usually the sum of task durations Usually close to the slowest task duration
Resource pressure Relatively low May be higher
Error handling Can be handled step by step Requires consideration of an overall failure strategy

4. Sequential and Concurrent Flow

flowchart TD
    A["Start executing tasks"] --> B{"Do tasks have dependencies?"}
    B -->|"Dependencies exist"| C["Execute sequentially"]
    B -->|"Independent"| D["Start concurrently"]
    C --> E["Wait for current task to complete"]
    E --> F["Get task result"]
    F --> G{"Are there more tasks?"}
    G -->|"Yes"| C
    G -->|"No"| H["Aggregate business results"]
    D --> I["Wait for all tasks"]
    I --> J{"Did all tasks succeed?"}
    J -->|"Yes"| H
    J -->|"No"| K["Handle failure"]
    K --> L["Degrade or recover"]
    L --> H

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style L fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

VIII. Combining Async / Await with Promise

Async / Await is built on top of Promise, and Promise's composition APIs remain important tools for organizing asynchronous tasks.

1. Promise.all

Wait for all tasks to succeed:

async function loadDashboard() {
    const [user, orders, products] = await Promise.all([
        getUser(),
        getOrders(),
        getProducts()
    ]);

    return {
        user,
        orders,
        products
    };
}

If any Promise rejects, the Promise returned by Promise.all rejects.

Other tasks are not automatically canceled as a result.

2. Promise.allSettled

When it is acceptable for some tasks to fail, you can use Promise.allSettled:

async function loadResources() {
    const results = await Promise.allSettled([
        getUser(),
        getOrders(),
        getProducts()
    ]);

    return results.map(result => {
        if (result.status === "fulfilled") {
            return result.value;
        }

        return null;
    });
}

Suited to batch data fetching and to business logic that can tolerate partial success.

3. Promise.race

Wait for whichever task settles first:

async function getFastestResult() {
    return await Promise.race([
        requestServerA(),
        requestServerB()
    ]);
}

Whichever one finishes first—whether it succeeds or fails—determines the overall result.