In asynchronous programming, async and await are used to handle asynchronous operations more effectively. Here’s the difference:
- async (Asynchronous Function)
- The async keyword is used to declare a function as asynchronous.
- An async function always returns a Promise implicitly, even if it contains synchronous code.
- Inside an async function, you can use await to pause execution until a Promise is resolved or rejected.
Example:
async function fetchData() {
return “Hello, World!”;
}
fetchData().then(console.log); // Output: Hello, World!
Even though fetchData returns a string, it is automatically wrapped in a Promise.
- await (Pausing Execution Until a Promise Resolves)
- The await keyword can only be used inside an async function.
- It pauses the execution of the function until the Promise resolves, making the code look synchronous.
- It simplifies working with Promises by eliminating .then() chaining.
Example:
async function fetchData() {
let promise = new Promise((resolve) => {
setTimeout(() => resolve(“Data received!”), 2000);
});
let result = await promise; // Waits for the promise to resolve
console.log(result);
}
fetchData(); // Output after 2 seconds: “Data received!”
Here, the function waits for the setTimeout to complete before logging the result.
Key Differences:
Feature | async | await |
Definition | Declares an asynchronous function | Pauses execution until a Promise resolves |
Returns | Always returns a Promise | Returns the resolved value of a Promise |
Usage | Before a function declaration | Inside an async function only |
Behavior | Makes a function asynchronous | Waits for async operations to complete |
Real-World Example: Fetching API Data using async and await
Let’s say we need to fetch user data from an API. Without async/await, we would use .then(), making the code slightly harder to read. Using async/await makes it cleaner and more readable.
Example: Fetching User Data
Without async/await (Using .then())
function getUserData() {
fetch(“https://jsonplaceholder.typicode.com/users/1”)
.then(response => response.json())
.then(data => console.log(“User Data:”, data))
.catch(error => console.error(“Error:”, error));
}
getUserData();
- This code fetches user data and logs it.
- But the .then() chain makes it a bit harder to read, especially if multiple asynchronous calls are needed.
With async/await (Cleaner & More Readable)
async function getUserData() {
try {
let response = await fetch(“https://jsonplaceholder.typicode.com/users/1”); // Wait for response
let data = await response.json(); // Wait for JSON conversion
console.log(“User Data:”, data);
} catch (error) {
console.error(“Error:”, error);
}
}
getUserData();
How This Works:
- fetch() returns a Promise, which await waits to resolve.
- response.json() is also a Promise, so await waits again.
- The try…catch block handles errors gracefully.
When to Use async/await?
✅ When working with APIs (like fetching data).
✅ When dealing with database queries.
✅ When handling file I/O operations.
✅ When writing event-driven code in JavaScript.