Node.js Async/Await

Node.js Async/Await
Async/Await is a modern way to write asynchronous code in Node.js.
It is built on top of Promises but looks and behaves like synchronous code — making it easier to read, write, and debug.
1. What is async?
A function becomes asynchronous when you add the async keyword.
Example:
An async function always returns a Promise.
2. What is await?
await is used inside an async function and makes JavaScript wait until a Promise is resolved or rejected.
Example:
Why Use Async/Await?
✔ Cleaner and more readable than Promises
✔ No callback hell
✔ Easy error handling using try...catch
✔ Looks like synchronous code
Async/Await Example with File Reading
Using fs.promises:
Async/Await With Custom Promise
Error Handling with Async/Await
Use try...catch for clean error handling:
Multiple Awaits (Sequential Execution)
Running Promises in Parallel
Instead of:
Use:
This runs both tasks at the same time = faster.
Rules for Async/Await
awaitworks only inside anasyncfunctionAsync functions always return a Promise
Use
try...catchto handle errorsCleanest method for asynchronous code
Async/Await vs Promises vs Callbacks
| Feature | Callbacks | Promises | Async/Await |
|---|---|---|---|
| Readability | Low | Medium | High |
| Error handling | Difficult | Easier | Very easy |
| Avoids callback hell | ❌ | ✔ | ✔✔ |
| Modern | No | Yes | Most modern |
