JavaScript Async / Await
JavaScript Async / Await
async and await are modern JavaScript features that make working with Promises easier and code more readable, avoiding the “callback hell.”
1️⃣ Async Functions
-
An
asyncfunction always returns a Promise. -
If a function returns a value, it is wrapped in a resolved Promise.
-
You can use
awaitonly inside async functions.
2️⃣ Await Keyword
-
awaitpauses the execution of the async function until the Promise resolves. -
It can only be used inside
asyncfunctions.
3️⃣ Error Handling with Try / Catch
4️⃣ Sequential vs Parallel Execution
Sequential Execution (Slower)
Parallel Execution (Faster)
5️⃣ Real World Example: Fetch API
6️⃣ Key Rules
-
Always use
awaitinsideasyncfunctions. -
asyncfunctions return a Promise. -
Use
try/catchto handle errors. -
Combine with
Promise.all()for parallel execution.
⭐ Summary Table
| Feature | Description |
|---|---|
async |
Declares an asynchronous function |
await |
Waits for a Promise to resolve |
| Error Handling | Use try / catch |
| Return Value | Always a Promise |
| Sequential Execution | await one by one |
| Parallel Execution | Promise.all([...]) |
