{"title":"How to Implement async/await in TypeScript?","content":"Implementing async/await in TypeScript is similar to JavaScript. First, ensure that your TypeScript version supports async/await. TypeScript versions 2.1 and above already support this feature.\n\nHere is a specific example demonstrating how to use async/await in TypeScript:\n\ntypescript\nasync function getUserData(userId: number): Promise<any> {\n try {\n const response = await fetch(`https://api.someservice.com/user/${userId}`);\n const data = await response.json();\n return data;\n } catch (error) {\n console.error('Error fetching user data:', error);\n throw error;\n }\n}\n\n\nIn this example, getUserData is an asynchronous function that attempts to fetch user data from an API. The async keyword declares a function as asynchronous, meaning it returns a Promise. The await keyword is used to wait for a Promise to resolve, pausing the function's execution until the Promise is resolved or rejected.\n\nTo use async/await correctly, you must handle potential errors, typically using try/catch statements to catch exceptions thrown by await.\n\nEnsure that your compilation target (target) and library (lib) settings in tsconfig.json are appropriately configured to support async/await. For example, you may need to set the target to "es2017" or higher, as async/await was introduced in ES2017. If the target environment already supports async/await, this configuration allows direct usage without further transpilation."}
TypeScript 中如何实现 async/await?
2月21日 17:11