Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
Async/await
is a powerful feature in TypeScript (and JavaScript) that simplifies asynchronous
programming by allowing you to write asynchronous code in a more synchronous
and readable way.
It builds on top of Promises and is widely used to work with asynchronous operations like network requests, file I/O, or database queries. Async/await is especially useful when dealing with callback-heavy code, making it more straightforward and error-resistant.
Here's a deep dive into how async and await work in TypeScript:
To use await
, you must define an async
function, which returns a Promise. An async
function is marked with the async keyword, and it can contain one or more await expressions. When you call an async function, it starts executing, and when an await expression is encountered, the function pauses until the promise it's waiting for is resolved.
javascriptasync function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
fetchData()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
In this example, fetchData
is an async function that fetches data from an API and parses it as JSON. The await
keyword is used to pause the function's execution until the promise returned by fetch is resolved.
Async/await simplifies error handling by allowing you to use try/catch
blocks, just like synchronous
code. If an error occurs in an await expression, it will be caught by the catch block.
javascriptasync function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('An error occurred:', error);
throw error; // Re-throw the error for further handling
}
}
You can use await
to execute multiple asynchronous operations concurrently and then wait for all of them to complete using Promise.all
. This is helpful when you have independent async
tasks that don't depend on each other.
javascriptasync function fetchDataConcurrently() {
const [result1, result2] = await Promise.all([
fetch('https://api.example.com/data1').then(response => response.json()),
fetch('https://api.example.com/data2').then(response => response.json())
]);
return { result1, result2 };
}
Async/await also simplifies the sequential execution of asynchronous
tasks. You can execute one asynchronous
operation after another, and each will await
the previous one to complete.
javascriptasync function fetchDataSequentially() {
const data1 = await fetch('https://api.example.com/data1').then(response => response.json());
const data2 = await fetch('https://api.example.com/data2').then(response => response.json());
return { data1, data2 };
}
You can nest async
functions to handle more complex scenarios or dependencies between asynchronous tasks.
However, be cautious not to over-nest, as it can lead to callback hell similar to deeply nested callbacks.
warningjavascriptasync function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
async function processAndSaveData() {
try {
const data = await fetchData();
// Process and save the data
} catch (error) {
console.error('An error occurred:', error);
}
}
Async/await in TypeScript simplifies asynchronous programming, making it more readable and manageable. It is particularly useful for handling asynchronous tasks in a structured and error-handling-friendly manner, improving the overall quality of your code.