Async/Await Tutorial

What is Async/Await?

Async/await is a syntactic sugar built on top of Promises. It allows you to write asynchronous code that looks and behaves a little more like synchronous code, making it easier to read and reason about.

Why Use Async/Await?

Before async/await, working with Promises could lead to deeply nested callbacks or complex Promise chains, which could be difficult to debug and maintain. Async/await simplifies the process by allowing you to use the `await` keyword to pause execution until a Promise resolves, without the need for callbacks or `.then()` chains.

            
                // Before async/await
                function fetchData() {
                    return new Promise(resolve => {
                        setTimeout(() => {
                            resolve('Data fetched!');
                        }, 1000);
                    });
                }

                // After async/await
                async function fetchDataAsync() {
                    const data = await fetchData();
                    console.log(data);
                }

                fetchDataAsync();
            
        

Basic Usage

Let's look at a simple example of fetching data from a URL using `fetch`. The `async` keyword before the function declaration tells JavaScript that this function contains asynchronous operations that can be awaited.

            
                async function getData() {
                    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
                    const data = await response.json();
                    console.log(data);
                    return data;
                }

                getData();
            
        

Error Handling

It's important to handle potential errors when working with asynchronous operations. You can use `try...catch` blocks to gracefully handle errors.

            
                async function fetchDataWithErrorHandling() {
                    try {
                        const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
                        if (!response.ok) {
                            throw new Error(`HTTP error! Status: ${response.status}`);
                        }
                        const data = await response.json();
                        console.log(data);
                    } catch (error) {
                        console.error('Error fetching data:', error);
                    }
                }

                fetchDataWithErrorHandling();