乐闻世界logo
搜索文章和话题

How can you implement async/await in TypeScript?

1个答案

1

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

  1. async Functions: Declare any function as asynchronous by adding the async keyword before the function declaration. This automatically makes the function return a Promise.

  2. await Expressions: Inside an async function, use the await keyword to wait for a Promise to resolve. This pauses the execution of the async function until the Promise completes and returns the result.

Example

Suppose we have an asynchronous function simulating data retrieval that returns a Promise:

typescript
function 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:

typescript
async 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

  • displayUser Function: This is an async function that waits for the result of fetchUserData. await can only be used within async functions.

  • Error Handling: It is recommended to use try/catch to handle potential errors. This is the standard approach for managing errors in async/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.

2024年7月20日 11:42 回复

你的答案