Node.js Promises
Subject: Node.js
What Is a Promise?
A Promise in JavaScript is an object that represents the eventual result of an asynchronous operation. It can be in one of three states:
- Pending: Initial state, not yet fulfilled or rejected
- Fulfilled: Operation completed successfully
- Rejected: Operation failed with an error
Why Use Promises in Node.js?
- Avoid deeply nested callbacks (callback hell)
- Better code readability and maintainability
- Support for chaining multiple operations
- Easier error handling with
.catch()
- Promises are the foundation of async/await
Syntax of a Promise
Example: Basic Promise
Output:
Converting Callback to Promise (Using fs.promises)
Node.js provides promise-based versions of many core APIs like fs
.
Promise Chaining
You can chain promises to execute async operations in sequence:
Output:
Handling Errors with .catch()
Errors in a promise chain are caught with .catch()
:
Promise Static Methods
Example: Promise.all()
Promise.all()
runs multiple promises in parallel and waits for all to complete.
Output:
Key Takeaways
- Promises provide a modern solution for asynchronous programming in Node.js
- Improve readability and maintainability over callbacks
- Support chaining via
.then()
and centralized error handling via.catch()
- Use built-in promise-based Node.js modules like
fs.promises
- Combine multiple promises with
Promise.all()
,Promise.race()
, etc.