TypeScript supports asynchronous programming using Promises and the async/await syntax, similar to JavaScript, but with added type safety. Here's an overview of how to use async in TypeScript and why it's beneficial:
async function fetchData(): Promise<Data> {
const response = await fetch('<https://api.example.com/data>');
return await response.json();
}
interface User {
id: number;
name: string;
}
async function getUser(id: number): Promise<User> {
const response = await fetch(`https://api.example.com/users/${id}`);
return await response.json();
}
async function fetchData(): Promise<Data> {
try {
const response = await fetch('<https://api.example.com/data>');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Failed to fetch data:", error);
throw error; // Re-throw or handle as needed
}
}
When you have multiple asynchronous operations that don't depend on each other, you can start them all at once and wait for all of them to complete, rather than executing them sequentially.
Promise.all()
async function fetchMultipleData(): Promise<[UserData, PostData]> {
const [userData, postData] = await Promise.all([
fetchUserData(),
fetchPostData()
]);
return [userData, postData];
}
Promise.allSettled()
Promise.all(), but waits for all Promises to settle (either fulfill or reject).async function fetchMultipleUsersWithStatus(ids: number[]): Promise<PromiseSettledResult<User>[]> {
const promises = ids.map(id => fetchUser(id));
return await Promise.allSettled(promises);
}
Promise.race()