TypeScript supports asynchronous programming using Promises and the async/await syntax, similar to JavaScript, but with added type safety. Here's an overview of how to use async in TypeScript and why it's beneficial:

Syntax

async function fetchData(): Promise<Data> {
    const response = await fetch('<https://api.example.com/data>');
    return await response.json();
}

Why use async in Typescript

  1. Type Safety:
  2. Better Error Handling:
  3. Improved Readability:
  4. Enhanced Maintainability:

Examples

Typing Promises

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

async function getUser(id: number): Promise<User> {
    const response = await fetch(`https://api.example.com/users/${id}`);
    return await response.json();
}

Error handling

async function fetchData(): Promise<Data> {
    try {
        const response = await fetch('<https://api.example.com/data>');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        console.error("Failed to fetch data:", error);
        throw error; // Re-throw or handle as needed
    }
}

Parallel execution

When you have multiple asynchronous operations that don't depend on each other, you can start them all at once and wait for all of them to complete, rather than executing them sequentially.

  1. Promise.all()
async function fetchMultipleData(): Promise<[UserData, PostData]> {
    const [userData, postData] = await Promise.all([
        fetchUserData(),
        fetchPostData()
    ]);
    return [userData, postData];
}
  1. Promise.allSettled()
async function fetchMultipleUsersWithStatus(ids: number[]): Promise<PromiseSettledResult<User>[]> {
    const promises = ids.map(id => fetchUser(id));
    return await Promise.allSettled(promises);
}
  1. Promise.race()