Node.js Promises
Node.js Promises
A Promise in Node.js is an object that represents the eventual completion (or failure) of an asynchronous operation.
Promises make asynchronous code:
-
Cleaner
-
Easier to read
-
Easier to manage
-
Avoid “callback hell”
✅ What Is a Promise?
A Promise has three states:
| State | Meaning |
|---|---|
| Pending | The async operation is still running |
| Fulfilled | The operation completed successfully |
| Rejected | The operation failed |
Basic Promise Example
⭐ Using Promises with Async Functions
Node.js provides promise-based APIs (like fs.promises):
Example: Reading a file with Promises
Promise Chaining
You can chain multiple .then() operations:
Handling Errors in Promises
Errors are handled using .catch():
Promise.all()
Runs multiple promises at the same time and waits for all to finish.
Output:
Promise.race()
Returns the result of the first completed promise:
Output:
Why Use Promises in Node.js?
✔ Avoid callback hell
✔ Better error handling
✔ Cleaner asynchronous code
✔ Works perfectly with async/await
Promises vs Callbacks
| Callbacks | Promises |
|---|---|
| Messy when nested | Cleaner chaining |
| Harder to handle errors | Easy .catch() |
| Callback hell | No callback hell |
| Older pattern | Modern approach |
