Implementing async/await in TypeScript is nearly identical to JavaScript because TypeScript is a superset of JavaScript and both support modern JavaScript features, including the async/await syntax introduced in ES2017. async/await simplifies writing and reading asynchronous code, making it resemble synchronous code more closely.
Using async/await Basic Syntax
-
asyncFunctions: Declare any function as asynchronous by adding theasynckeyword before the function declaration. This automatically makes the function return a Promise. -
awaitExpressions: Inside anasyncfunction, use theawaitkeyword to wait for a Promise to resolve. This pauses the execution of theasyncfunction until the Promise completes and returns the result.
Example
Suppose we have an asynchronous function simulating data retrieval that returns a Promise:
typescriptfunction fetchUserData(userId: string): Promise<any> { return new Promise((resolve) => { setTimeout(() => { resolve({id: userId, name: "John Doe", email: "john@example.com"}); }, 1000); }); }
Now, use async/await to call this function:
typescriptasync function displayUser() { try { const userData = await fetchUserData("u123"); console.log(`User Name: ${userData.name}`); console.log(`Email: ${userData.email}`); } catch (error) { console.error("Error fetching user data:", error); } } displayUser();
Explanation
-
displayUserFunction: This is anasyncfunction that waits for the result offetchUserData.awaitcan only be used withinasyncfunctions. -
Error Handling: It is recommended to use
try/catchto handle potential errors. This is the standard approach for managing errors inasync/await.
Summary
Using async/await clarifies asynchronous code structure and improves manageability. It reduces reliance on callback functions, making code resemble traditional synchronous code for better readability and maintainability. In TypeScript, async/await integrates with the type system to provide enhanced type checking and error detection.