await Keyword in Typescript

Do you want to know about the Typescript await keyword? In this Typescript tutorial, I will explain how to use the await keyword in Typescript with examples and complete code.

The await keyword in TypeScript is used inside async functions to pause the execution until a Promise is resolved. It simplifies handling asynchronous operations, allowing code to be written in a more readable, synchronous-like manner.

What is the Await Keyword in TypeScript?

The await keyword in Typescript is used to wait for a Promise to resolve before continuing the execution of the code. It can only be used inside an async function. This syntactic feature simplifies writing asynchronous code by allowing developers to write code in a synchronous manner while still benefiting from the non-blocking advantages of asynchronous operations.

Syntax of await in Typescript

Here is the syntax of await in Typescript.

async function exampleFunction() {
    let result = await someAsyncOperation();
    console.log(result);
}

Here someAsyncOperation() is a function that returns a Promise. The await keyword is used to wait for the Promise to resolve, and the resolved value is then stored in result.

Typescript await Keyword Example

Let us check out a few examples of how to use the await keyword in Typescript.

Example 1: Fetching Data from an API

One common use case of the await keyword is fetching data from an API in Typescript. Here is a sample code:

async function fetchData() {
    try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

fetchData();

In this example, fetch() returns a Promise, and we use await to pause the execution until the Promise resolves. We then convert the response to JSON and log it to the console.

See also  type keyword in Typescript

Example 2: Handling Multiple Asynchronous Operations

The await keyword shines when you need to handle multiple asynchronous operations in sequence.

async function getUserData(userId: number) {
    try {
        let userResponse = await fetch(`https://api.example.com/users/${userId}`);
        let userDetails = await userResponse.json();

        let postsResponse = await fetch(`https://api.example.com/users/${userId}/posts`);
        let posts = await postsResponse.json();

        return { userDetails, posts };
    } catch (error) {
        console.error('Error fetching user data:', error);
    }
}

getUserData(1).then(data => console.log(data));

Here, we first fetch user details and then fetch the user’s posts. Each operation waits for the previous one to complete.

Example 3: Using Await in a Loop

await can also be used inside loops in Typescript, which is handy for sequential asynchronous operations.

async function fetchMultipleUsers(userIds: number[]) {
    let users = [];
    for (let id of userIds) {
        let response = await fetch(`https://api.example.com/users/${id}`);
        let userData = await response.json();
        users.push(userData);
    }
    return users;
}

fetchMultipleUsers([1, 2, 3]).then(users => console.log(users));

In this example, user data for each ID in the userIds array is fetched one after the other.

Best Practices of using await in Typescript

Here are some best practices you can follow while using await in Typescript.

  • Use await within try…catch blocks to handle errors gracefully.
  • Be mindful of using await inside loops, as it can lead to performance issues if not managed correctly.
  • Combine await with Promise.all() for parallel asynchronous operations.

Conclusion

The await keyword in TypeScript simplifies handling asynchronous operations, making the code more readable and easier to maintain. By effectively utilizing await with async functions, developers can write asynchronous code that resembles synchronous code, reducing complexity and improving readability.

I have explained how to use the await keyword in TypeScript in this tutorial with three examples.

See also  How To Split String And Get Last Element In Typescript?

You may also like:

>