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! π₯
β 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.
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)
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: