JavaScript Async and Await

JavaScript Async and Await
JavaScript Async and Await make asynchronous JavaScript easier to read and write. They are built on top of Promises, but feel more like normal, synchronous code.
Why Async/Await?
Before async/await, we used:
Callbacks → callback hell
Promises with
.then()→ better, but still nested sometimes
async/await solves this by making async code look clean and sequential
The async Keyword
Used before a function
Always returns a Promise
If you return a value, JavaScript automatically wraps it in a Promise
The await Keyword
Used inside an async function only
Pauses execution until the Promise resolves
Makes async code behave like synchronous code
How Async/Await Works (Flow)
- JavaScript waits at
await Other code can run- Execution resumes when Promise resolves
Async/Await with fetch() (Real Example)
- No
.then()chaining - Clean & readable
Error Handling with try...catch
- Errors are handled just like normal JavaScript
Multiple Await Calls (Sequential vs Parallel)
Sequential (Slower)
Parallel (Faster)
Async Arrow Function
Common Mistakes
- Using
awaitoutsideasync Forgettingtry...catchAssumingawaitblocks the whole program (it doesn’t!)
Quick Summary
| Feature | Description |
|---|---|
async | Makes a function return a Promise |
await | Waits for a Promise to resolve |
try...catch | Handles async errors |
| Cleaner | Replaces .then() chains |

