Promises in Node

Promises represent a future value and chain cleanly with then/catch.

Syntaxpromise.then(onOk).catch(onErr);

A promise represents a value that will arrive later. It is pending, then either fulfilled or rejected.

Consuming promises

  • .then() — runs on success.
  • .catch() — runs on failure.
  • .finally() — always runs at the end.

Most modern Node APIs (like fs/promises) return promises directly.

Example

Example · javascript
const fs = require('fs/promises');

fs.readFile('data.txt', 'utf8')
  .then((text) => console.log('Length:', text.length))
  .catch((err) => console.error('Error:', err.message))
  .finally(() => console.log('Done'));

When to use it

  • An auth service chains `.then()` calls to fetch a user, verify a password, and issue a JWT token in a readable sequential flow.
  • A data aggregation job uses `Promise.all()` to fire three database queries simultaneously and wait for all results before generating a report.
  • A retry wrapper wraps a flaky API call in a Promise and rejects with a custom error after the max attempt count is exceeded.

More examples

Create and resolve a Promise

Wraps a synchronous result in a Promise, then chains `.then()` for success and `.catch()` for errors.

Example · js
const fetchUser = (id) => new Promise((resolve, reject) => {
  if (id <= 0) return reject(new Error('Invalid ID'));
  resolve({ id, name: 'Alice' });
});

fetchUser(1)
  .then(user => console.log(user))
  .catch(err  => console.error(err.message));

Chain multiple promises

Chains two `.then()` transformations on a file-read promise -- each returns the value for the next step.

Example · js
const { readFile } = require('fs/promises');

readFile('raw.txt', 'utf8')
  .then(text  => text.trim().toUpperCase())
  .then(upper => console.log(upper))
  .catch(err  => console.error('Failed:', err.message));

Promise.all for parallel tasks

Uses `Promise.all` to read three files in parallel and destructure all results when every promise resolves.

Example · js
const { readFile } = require('fs/promises');

Promise.all([
  readFile('config.json',  'utf8'),
  readFile('schema.json',  'utf8'),
  readFile('defaults.json','utf8'),
]).then(([config, schema, defaults]) => {
  console.log('All loaded');
});

Discussion

  • Be the first to comment on this lesson.