In the world of modern web development, handling asynchronous operations is a common task. JavaScript provides several ways to deal with asynchronous code, such as callbacks, promises, and async/await. Among these, async/await offers a more readable and manageable syntax for writing asynchronous code, making it easier to understand and maintain.
Async/await is built on top of promises and simplifies the handling of asynchronous operations by allowing you to write asynchronous code that looks synchronous. The async keyword declares a function as an asynchronous function, which means it returns a promise. Inside an async function, you can use the await keyword to pause the execution until a promise is resolved or rejected.
async always returns a promise.Let's dive into some examples to understand how async/await works in TypeScript.
Suppose we have a function that fetches user data from an API. We can use async/await to make the code more readable.
1async function getUserData(userId: number): Promise<User> {2const response = await fetch(`https://api.example.com/users/${userId}`);3if (!response.ok) {4throw new Error('Failed to fetch user data');5}6return response.json();7}89getUserData(1)10.then(user => console.log(user))11.catch(error => console.error(error));
In this example, the getUserData function is declared as async, and it uses await to wait for the fetch operation to complete. If the response is not OK, an error is thrown. The calling code uses .then() and .catch() to handle the resolved promise or any errors.
Async/await also makes it easy to handle multiple promises in sequence or parallel.
1async function fetchMultipleUsers(userIds: number[]): Promise<User[]> {2const users = [];3for (const userId of userIds) {4const user = await getUserData(userId);5users.push(user);6}7return users;8}910fetchMultipleUsers([1, 2, 3])11.then(users => console.log(users))12.catch(error => console.error(error));
In this example, the fetchMultipleUsers function fetches data for multiple users one by one. The for...of loop iterates over each user ID, and await is used to wait for each fetch operation to complete before moving on to the next.
If you want to execute multiple promises in parallel, you can use Promise.all.
1async function fetchMultipleUsersInParallel(userIds: number[]): Promise<User[]> {2const userPromises = userIds.map(userId => getUserData(userId));3return await Promise.all(userPromises);4}56fetchMultipleUsersInParallel([1, 2, 3])7.then(users => console.log(users))8.catch(error => console.error(error));
Here, Promise.all is used to wait for all the promises in the userPromises array to resolve. The await keyword ensures that the function only proceeds after all fetch operations are completed.
Now that you have a good understanding of async/await in TypeScript, the next step is to learn about error handling in asynchronous code. Understanding how to handle errors effectively will make your asynchronous functions more robust and reliable.
Stay tuned for more tutorials on advanced TypeScript topics!