async Keyword in Typescript

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

The async keyword in TypeScript is used to define an asynchronous function that returns a Promise, simplifying asynchronous operations. Inside an async function, you can use the await keyword to pause execution until a Promise is resolved, leading to cleaner and more readable code. This approach is particularly useful for handling operations like API requests or file reading without blocking the main execution thread.

What is the async Keyword in Typescript?

The async keyword, introduced in ES2017, is used to declare an asynchronous function, which returns a Promise. This keyword enables the use of await within the function, allowing developers to write asynchronous code in a more synchronous-looking manner, thus improving readability and maintainability.

Syntax of async Keyword in Typescript

Here’s a simple syntax of an async function in Typescript.

async function fetchData() {
    // asynchronous operations here
}

How Does async Work in Typescript?

When you declare a function with async, it transforms the function into a promise-based one. Whatever you return from the function is automatically wrapped in a Promise.resolve(), allowing you to use .then() and .catch() on it, just like any other promise.

Example 1: Basic Async Function

Let’s start with a basic example of how to use the async in Typescript.

async function getUser() {
    return "John Doe";
}

getUser().then(user => console.log(user)); // Output: John Doe

In this example, getUser is an asynchronous function that returns a string. Despite not having any asynchronous operations, the returned value is wrapped in a promise.

Example 2: Using await with async

The true power of async functions comes into play when combined with await. The await keyword can only be used inside async functions, and it pauses the function execution until the promise is resolved or rejected.

async function fetchUserData(userId: number) {
    let response = await fetch(`https://api.example.com/users/${userId}`);
    let data = await response.json();
    return data;
}

fetchUserData(1).then(user => console.log(user));

In this example, fetchUserData fetches user data from an API. The function execution pauses at each await until the fetch operation and the JSON parsing are complete.

Error Handling in Async/Await

To handle errors in async/await, you can use try-catch blocks:

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

fetchPosts().then(posts => console.log(posts));

Best Practices for using async in Typescript

  1. Error Handling: Always use try-catch blocks for error handling in async functions to avoid unhandled promise rejections.
  2. Avoiding Callback Hell: Use async/await to write cleaner code and avoid the callback hell commonly associated with promises.
  3. Parallel Execution: When dealing with multiple independent promises, use Promise.all to execute them in parallel.

Conclusion

The async keyword in TypeScript simplifies handling asynchronous operations, making code more readable and maintainable. By turning functions into promises and allowing the use of await, it streamlines the process of writing asynchronous code. Remember to handle errors properly and leverage Promise.all for parallel tasks to make the most out of this powerful feature.

In this tutorial, I have explained how to work with the async keyword in Typescript with examples.

You may also like:

>