Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Async/Await

Async/await makes asynchronous code easier to read and maintain. It allows us to write Promise-based operations in a style that looks similar to sequential code.

Learning objective: Understand the async and await keywords, asynchronous return types, error handling, API calls, and parallel execution.

1. What Is Async/Await?

async and await are JavaScript features supported by TypeScript. They make Promise-based asynchronous operations easier to express.

The async keyword marks a function as asynchronous. The await keyword waits for a Promise to settle inside an async function and evaluates to its fulfilled value. If the Promise rejects, the await expression throws the rejection reason.

⚙️
async

Declares an asynchronous function that returns a Promise.

⏳
await

Waits for a Promise's result inside the async function.

✅
Result

Continues execution with the result or handles an error.

Important: await pauses the progress of the surrounding async function, not the entire JavaScript application. Other work can continue while the asynchronous operation is pending.

2. Basic Async/Await Syntax

Use async before the function declaration and await before the Promise-based operation.

async function getMessage(): Promise<string> {
    return "Welcome to TypeScript";
}

async function displayMessage(): Promise<void> {
    const message: string = await getMessage();

    console.log(message);
}

displayMessage();

Expected Output

Welcome to TypeScript

Explanation

  1. getMessage() is an async function.
  2. Its return value is wrapped in a fulfilled Promise.
  3. await getMessage() obtains the string value.
  4. displayMessage() prints the message.

3. Async Function Return Types

An async function always returns a Promise. The type inside the Promise describes the fulfilled value.

Return Type Meaning Example
Promise<string> The Promise fulfills with a string. async function getName(): Promise<string>
Promise<number> The Promise fulfills with a number. async function getMarks(): Promise<number>
Promise<boolean> The Promise fulfills with a boolean. async function isValid(): Promise<boolean>
Promise<void> The function does not provide a meaningful return value. async function saveData(): Promise<void>

Example

async function getStudentMarks(): Promise<number> {
    return 85;
}

async function showMarks(): Promise<void> {
    const marks: number = await getStudentMarks();

    console.log("Student Marks: " + marks);
}

showMarks();

Expected Output

Student Marks: 85
Remember: An async function declared with Promise<number> should return a number value, not a regular Promise annotation written as number.

4. Using Await with a Promise

The await keyword allows the function to continue after the Promise settles. In the following example, a timer simulates a delayed result.

function getCourse(): Promise<string> {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve("Full Stack Development");
        }, 2000);
    });
}

async function displayCourse(): Promise<void> {
    console.log("Loading course...");

    const course: string = await getCourse();

    console.log("Course: " + course);
}

displayCourse();

Expected Output

Loading course...
Course: Full Stack Development

The second message appears after approximately two seconds.

5. Async/Await Execution Flow

When an awaited Promise is pending, the current async function suspends. Once the Promise settles, the function continues or throws an error.

▶️
Call Function

Start execution

→
⏳
Await Promise

Suspend this function's progress

→
📤
Continue or Throw

Use the value or handle the rejection

Note: Awaiting a Promise does not mean the browser or server stops all other work. The JavaScript runtime can continue processing other tasks.

6. Error Handling with try, catch, and finally

A rejected Promise causes an awaited expression to throw. Use try-catch to handle errors and finally for cleanup operations.

async function processPayment(): Promise<void> {
    try {
        console.log("Processing payment...");

        const paymentSuccessful = false;

        if (!paymentSuccessful) {
            throw new Error("Payment failed");
        }

        console.log("Payment completed successfully");
    }
    catch (error: unknown) {
        if (error instanceof Error) {
            console.log("Error: " + error.message);
        } else {
            console.log("An unknown error occurred");
        }
    }
    finally {
        console.log("Payment process finished");
    }
}

processPayment();

Expected Output

Processing payment...
Error: Payment failed
Payment process finished

Purpose of Each Block

  • try contains the operation that may fail.
  • catch handles a thrown error or awaited Promise rejection.
  • finally runs whether the try block succeeds or fails, unless control leaves the execution context in an unusual way.

7. Calling an API Using Async/Await

The browser's fetch() API returns a Promise. We can await the response and then parse the JSON data.

interface User {
    id: number;
    name: string;
    email: string;
}

async function getUser(): Promise<void> {
    try {
        const response = await fetch(
            "https://jsonplaceholder.typicode.com/users/1"
        );

        if (!response.ok) {
            throw new Error("HTTP error: " + response.status);
        }

        const user: User = await response.json();

        console.log("User ID: " + user.id);
        console.log("User Name: " + user.name);
        console.log("User Email: " + user.email);
    }
    catch (error: unknown) {
        if (error instanceof Error) {
            console.log("Request failed: " + error.message);
        }
    }
}

getUser();

Expected Output

User ID: 1
User Name: Leanne Graham
User Email: Sincere@april.biz
Important: This example requires network access to the sample API. Actual requests can fail. Also, TypeScript's type annotation does not validate incoming JSON at runtime; production applications should validate external data before trusting it.

8. Sequential Async Operations

If the second operation depends on the result of the first operation, await them in sequence.

function getStudentId(): Promise<number> {
    return Promise.resolve(101);
}

function getStudentName(id: number): Promise<string> {
    return Promise.resolve("Student ID: " + id);
}

async function displayStudent(): Promise<void> {
    const id = await getStudentId();
    console.log("ID received: " + id);

    const name = await getStudentName(id);
    console.log(name);
}

displayStudent();

Expected Output

ID received: 101
Student ID: 101
Use sequential execution when: a later operation needs the result of an earlier operation, such as obtaining a student ID before fetching that student's details.

9. Parallel Async Operations with Promise.all()

If multiple operations are independent, start them together and await Promise.all(). This can reduce total waiting time.

function getCourseName(): Promise<string> {
    return new Promise((resolve) => {
        setTimeout(() => resolve("TypeScript"), 1000);
    });
}

function getStudentCount(): Promise<number> {
    return new Promise((resolve) => {
        setTimeout(() => resolve(25), 1000);
    });
}

async function loadDashboard(): Promise<void> {
    const [courseName, studentCount] = await Promise.all([
        getCourseName(),
        getStudentCount()
    ]);

    console.log("Course: " + courseName);
    console.log("Students: " + studentCount);
}

loadDashboard();

Expected Output

Course: TypeScript
Students: 25

Both simulated operations start before the application waits for their combined result. They each take approximately one second, instead of requiring two sequential one-second waits.

10. Sequential vs Parallel Execution

Feature Sequential Parallel Coordination
How it works Await one operation before starting the next. Start independent operations before awaiting their combined result.
Use case Second task depends on the first task. Tasks do not depend on each other's results.
Typical code await taskOne(); await taskTwo(); await Promise.all([taskOne(), taskTwo()]);
Performance Can take longer when waits are independent. Can reduce total waiting time for independent operations.
Industry tip: Do not automatically make every operation parallel. Check whether tasks depend on each other, consider server limits, and decide how partial failures should be handled.

11. Common Async/Await Mistakes

Forgetting await

Without await, a function call may give you a Promise instead of its fulfilled value.

Incorrect return type

Async functions return Promises. Use types such as Promise<string> or Promise<void>.

Missing error handling

A rejected Promise awaited inside an async function can throw. Handle failures appropriately using try-catch.

Using sequential awaits unnecessarily

Independent operations can often be started together with Promise.all().

Assuming fetch rejects for every HTTP error

HTTP error responses such as 404 normally still fulfill the fetch Promise. Check response.ok explicitly.

Using await outside a valid context

In ordinary TypeScript function code, use await inside an async function. Top-level await depends on the module and compiler setup.

Summary

  • async declares a function that returns a Promise.
  • await waits for a Promise's result inside the async function.
  • Async functions use return types such as Promise<string> and Promise<void>.
  • Use try-catch-finally for error handling and cleanup.
  • Use fetch() and await to make and handle API requests.
  • Use sequential awaits when tasks depend on each other.
  • Use Promise.all() when independent operations can run together.
  • Always consider failures, response validation, and project requirements.