Async/await in TypeScript

In the whirlwind of asynchronous tasks, callbacks can create nested code monsters and leave you yearning for simpler ways. Enter the magical duo of async and await in TypeScript, your knights in shining asynchronous armor.

What is async/await?

Think of async like a choreographer setting the stage for asynchronous operations. It marks a function as able to contain asynchronous code. And just like dancers waiting for their cue, you use await within an async function to pause execution until a promise resolves. No more intricate callback chains!

Here's how it works:

Defining an async function:

async function fetchData(url: string): Promise<any> { const response = await fetch(url); const data = await response.json(); return data; }

Consuming the async function

fetchData('https://api.example.com/data') .then(data => { console.log('Data fetched successfully:', data); }) .catch(error => { console.error('Error fetching data:', error); });

Sequential async/await

async function sequentialAsyncOperations() { try { const data1 = await fetchData(); console.log(data1); const data2 = await processData(data1); console.log(`Processed data: ${data2}`); } catch (error) { console.error(error.message); } } sequentialAsyncOperations();

Using async/await allows for a more sequential and linear representation of asynchronous operations. In this example, the processData function is called only after the completion of the fetchData operation.

Error Handling with async/await

async function fetchDataWithError(): Promise<string> { return new Promise((_, reject) => { setTimeout(() => { reject(new Error("Error fetching data!")); }, 2000); }); } async function handleAsyncError() { try { const data = await fetchDataWithError(); console.log(data); } catch (error) { console.error(`Caught an error: ${error.message}`); } } handleAsyncError();

async/await simplifies error handling, as errors can be caught using standard try/catch blocks. In this example, the handleAsyncError function catches an error thrown by the fetchDataWithError function.

Concurrent async/await

async function concurrentAsyncOperations() { try { const [data1, data2] = await Promise.all([fetchData(), fetchData()]); console.log(data1, data2); } catch (error) { console.error(error.message); } } concurrentAsyncOperations();

async/await can also be used with Promise.all to handle multiple asynchronous operations concurrently. In this example, the concurrentAsyncOperations function awaits the resolution of both promises returned by fetchData simultaneously.

Handling multiple promises

async function getParallelData() { const userPromise = fetchData('https://api.example.com/users/1'); const postPromise = fetchData('https://api.example.com/posts/1'); const [user, post] = await Promise.all([userPromise, postPromise]); console.log('User:', user); console.log('Post:', post); } getParallelData();

With async and await, you can navigate the world of asynchronous operations with grace and control. Embrace their power, simplify your code, and experience the joy of dancing with asynchronous delights!

Conclusion

The async/await in TypeScript provides a clean and concise way to handle asynchronous code, making it easier to understand and maintain. It improves the readability of code that involves asynchronous operations, reducing the need for nested callbacks and promoting a more synchronous coding style.