Concept of async and await in JavaScript
async and await are used in asynchronous programming in JavaScript. They help us write cleaner, more readable, and more manageable asynchronous code without using complex callback functions or Promise chains.
🔸 Why Do We Need async/await?
JavaScript is single-threaded, meaning it executes one operation at a time. However, sometimes we need to perform long-running tasks like:
- Fetching data from a server (API calls)
- Reading files
- Accessing databases
- Waiting for user input
If JavaScript waits for each task to complete before moving to the next, the app becomes slow and unresponsive. To avoid this, we use asynchronous programming.
🔹 async Function
An async function always returns a Promise. This means the function runs in the background and does not block the execution of other code.
🔹 Example:
Here, fetchData() returns a Promise that resolves to "Hello, World!".
🔹 await Keyword
The await keyword pauses the execution of an async function until a Promise is resolved.
🔹 Example:
✅ What Happens Here?
fetch()returns a Promise, which is awaited.await response.json()waits for the JSON data.console.log(data)runs only after the data is available.
🚀 Without await, JavaScript would move to the next line before fetch() completes, leading to undefined or incomplete data.
🔸 Key Benefits of async/await
✅ Code looks synchronous & easy to read
✅ Avoids callback hell (nested callbacks)
✅ Better error handling with try...catch
🔹 Handling Errors in async/await
We can use try...catch to handle errors in an async function.
🔹 Example:
If an error occurs, catch will handle it gracefully instead of crashing the program.
🔸 Comparison: async/await vs Promises
| Feature | Promises (.then/.catch) | async/await |
|---|---|---|
| Syntax | Callback-based chaining | Looks like synchronous code |
| Readability | Harder (nested .then()) | Easier, cleaner |
| Error Handling | .catch() needed | try...catch is simpler |
| Performance | Similar | Similar |
🔹 Example with Promises (.then/.catch)
🔹 Same Example with async/await
🎯 Both do the same thing, but async/await is cleaner and more readable!
🔹 When to Use async/await?
✅ When dealing with APIs, databases, or file reading
✅ When you need sequential execution of async tasks
✅ When you want to handle errors easily with try...catch
🔥 Final Thought
async/await makes JavaScript asynchronous code more readable, maintainable, and easier to debug. It's a powerful tool for working with Promises in a cleaner way.