A
Async/Await
Async/await provides a cleaner syntax for working with Promises while maintaining full type safety.
Code
typescript
1// Basic async function2async function fetchData(): Promise<string> {3 return "Data fetched!";4}5 6// Async function with await7interface User {8 id: number;9 name: string;10 email: string;11}12 13async function getUser(id: number): Promise<User> {14 // Simulating API call15 await new Promise((resolve) => setTimeout(resolve, 100));16 17 return {18 id,19 name: `User ${id}`,20 email: `user${id}@example.com`,21 };22}23 24// Error handling with try/catch25async function getUserSafely(id: number): Promise<User | null> {26 try {27 const user = await getUser(id);28 return user;29 } catch (error) {30 console.error("Failed to fetch user:", error);31 return null;32 }33}34 35// Sequential async operations36async function processUsers(ids: number[]): Promise<User[]> {37 const users: User[] = [];38 39 for (const id of ids) {40 const user = await getUser(id);41 users.push(user);42 console.log(`Processed: ${user.name}`);43 }44 45 return users;46}47 48// Parallel async operations49async function processUsersParallel(ids: number[]): Promise<User[]> {50 const userPromises = ids.map((id) => getUser(id));51 const users = await Promise.all(userPromises);52 return users;53}54 55// Async IIFE (Immediately Invoked Function Expression)56(async () => {57 console.log("Starting...");58 59 const user = await getUser(1);60 console.log(`Got user: ${user.name}`);61 62 const users = await processUsersParallel([2, 3, 4]);63 console.log(`Got ${users.length} users in parallel`);64 65 console.log("Done!");66})();Run this example locally
$ npx ts-node async/async-await.ts