Difference between async and await

In asynchronous programming, async and await are used to handle asynchronous operations more effectively. Here’s the difference:

  1. 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:

Even though fetchData returns a string, it is automatically wrapped in a Promise.

  1. 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:

Here, the function waits for the setTimeout to complete before logging the result.

Key Differences:

Featureasyncawait
DefinitionDeclares an asynchronous functionPauses execution until a Promise resolves
ReturnsAlways returns a PromiseReturns the resolved value of a Promise
UsageBefore a function declarationInside an async function only
BehaviorMakes a function asynchronousWaits 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())

  • 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)

How This Works:

  1. fetch() returns a Promise, which await waits to resolve.
  2. response.json() is also a Promise, so await waits again.
  3. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Protected with IP Blacklist CloudIP Blacklist Cloud

This site uses Akismet to reduce spam. Learn how your comment data is processed.