0
0
Node.jsframework~5 mins

Promise chaining in Node.js

Choose your learning style9 modes available
Introduction
Promise chaining helps run multiple tasks one after another without confusing code. It makes handling steps that depend on each other easy and clear.
When you want to do one task after another, like loading data then processing it.
When you have several steps that depend on the result of the previous step.
When you want to avoid deeply nested callbacks that are hard to read.
When you want to handle errors in one place after many steps.
When you want to keep your code clean and easy to follow for asynchronous tasks.
Syntax
Node.js
function task1() {
  return new Promise((resolve, reject) => {
    // do something
    const result1 = 'result1';
    resolve(result1);
  });
}

function task2(previousResult) {
  return new Promise((resolve, reject) => {
    // use previousResult
    const result2 = 'result2';
    resolve(result2);
  });
}

task1()
  .then(result1 => task2(result1))
  .then(result2 => {
    // use result2
  })
  .catch(error => {
    // handle any error from task1 or task2
  });
Each .then() waits for the previous Promise to finish and uses its result.
Use .catch() at the end to handle errors from any step in the chain.
Examples
Simple chain where each step uses the previous value. Prints 10.
Node.js
Promise.resolve(5)
  .then(value => value * 2)
  .then(value => console.log(value));
Shows error handling in the chain. Prints 'Oops'.
Node.js
Promise.resolve()
  .then(() => {
    throw new Error('Oops');
  })
  .catch(error => console.log(error.message));
Each .then returns a Promise, chaining multiple async steps. Prints 3.
Node.js
Promise.resolve(1)
  .then(value => Promise.resolve(value + 1))
  .then(value => Promise.resolve(value + 1))
  .then(value => console.log(value));
If an error happens, later .then steps are skipped and .catch runs.
Node.js
Promise.resolve(10)
  .then(value => value + 5)
  .then(value => { throw new Error('Fail'); })
  .then(value => console.log('Won\'t run'))
  .catch(error => console.log('Error caught:', error.message));
Sample Program
This program fetches a number, adds five, then multiplies by two, showing each step's result. It uses Promise chaining to run these steps in order.
Node.js
function fetchNumber() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(10);
    }, 500);
  });
}

function addFive(number) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(number + 5);
    }, 500);
  });
}

function multiplyByTwo(number) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(number * 2);
    }, 500);
  });
}

fetchNumber()
  .then(result => {
    console.log('Fetched number:', result);
    return addFive(result);
  })
  .then(result => {
    console.log('After adding five:', result);
    return multiplyByTwo(result);
  })
  .then(result => {
    console.log('After multiplying by two:', result);
  })
  .catch(error => {
    console.error('Error:', error);
  });
OutputSuccess
Important Notes
Promise chaining runs tasks one after another, waiting for each to finish.
Time complexity depends on the tasks inside the Promises, not the chaining itself.
Common mistake: forgetting to return a Promise inside .then, which breaks the chain.
Use chaining when steps depend on each other's results; use Promise.all for parallel tasks.
Summary
Promise chaining helps run asynchronous tasks in order, using .then() for each step.
Always return a Promise inside .then() to keep the chain working.
Use .catch() at the end to handle errors from any step in the chain.