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

  1. Create a promise: const p = new Promise((resolve, reject) => { ... });.
  2. Resolve on success: resolve(value);.
  3. Reject on failure: reject(new Error('Failed'));.
  4. Consume the promise: p.then(val => ...).catch(err => ...);.
  5. 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.