JavaScript uses asynchronous programming to handle tasks like fetching data, handling files, and timers. Async/Await provides a cleaner, more readable way to handle asynchronous operations compared to Promises and Callbacks. Let’s break it down! πŸ”₯


πŸ”Ή What is Async/Await? πŸ€”

βœ… Async/Await is syntactic sugar over Promises. It makes asynchronous code look and behave more like synchronous code while still being non-blocking.

βœ… async is used to declare a function that returns a Promise.

βœ… await is used to pause the function execution until a Promise is resolved.

πŸ” Before Async/Await: Using Promises

function fetchData() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve("Data received βœ…");
        }, 2000);
    });
}

fetchData().then(data => console.log(data));
console.log("Fetching data...");

Output:

Fetching data...
(Data received βœ… after 2 sec)

🎯 Using Async/Await – Cleaner Code!

async function getData() {
    console.log("Fetching data...");
    let data = await fetchData(); // Wait for Promise to resolve
    console.log(data);
}

getData();

Output:

Fetching data...
(Data received βœ… after 2 sec)

πŸ›‘ Key Difference: