You can use the async and await keywords to call an asynchronous method in typescript.
Define an Async Method: Use async to declare a method that returns a Promise. This allows you to perform asynchronous operations.
async function fetchData(): Promise<string> {
return "Hello, Async World!";
}
Call the Async Method: To execute the method, use await within another async function:
async function callFetchData() {
const result = await fetchData();
console.log(result);
}
callFetchData();
Error Handling: Always wrap asynchronous calls in a try-catch block to handle potential errors.
async function safeCall() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error("The error is:", error);
}
}
Real-World Example (API Call): Here's how to make an API request:
const fetchUsers = async (): Promise<void> => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
console.log(users);
} catch (error) {
console.error("Something went wrong fetching users:", error);
}
};
fetchUsers();