Typescript async await
Created By: chatGPT
TypeScript provides support for asynchronous programming through the use of
async
and await
. These keywords allow you to write asynchronous code in a more readable format, almost resembling synchronous code. By leveraging async
functions, you can simplify the handling of promises without the need for chaining .then()
and .catch()
. Here's a basic overview of how to use them.async function fetchData(url: string): Promise<any> {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return await response.json();
}
To use
async
and await
, first you need to declare the function with the async
keyword. Then, within that function, you can use await
to pause execution until the promise is resolved. If the promise is rejected, it will throw an error that can be caught using a try/catch block.async function loadData() {
try {
const data = await fetchData('https://api.example.com/data');
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
This structure helps manage asynchronous operations more cleanly. You can also have multiple await statements in an async function, but keep in mind that if you await multiple promises sequentially, it could lead to performance issues. In such cases, consider using
Promise.all()
to execute them concurrently.async function fetchMultipleData() {
try {
const [data1, data2] = await Promise.all([
fetchData('https://api.example.com/data1'),
fetchData('https://api.example.com/data2')
]);
console.log(data1, data2);
} catch (error) {
console.error('Error fetching multiple data:', error);
}
}