How to use promises in Node.js
· Category: Node.js
Short answer
A Promise represents a value that may not exist yet but will be resolved at some point in the future. Use .then() for success, .catch() for errors, and .finally() for cleanup.
Steps
- Create a promise:
const p = new Promise((resolve, reject) => { ... });. - Resolve on success:
resolve(value);. - Reject on failure:
reject(new Error('Failed'));. - Consume the promise:
p.then(val => ...).catch(err => ...);. - Convert callback-based functions with
util.promisify.
Tips
- Chain multiple
.then()calls to run asynchronous tasks in sequence. - Always attach a
.catch()handler to prevent unhandled promise rejections.
Common issues
- Returning a value inside
.then()wraps it in a resolved promise automatically. - Errors thrown inside a
.then()callback are caught by the next.catch()in the chain.