0
0
Javascriptprogramming~5 mins

Promise chaining in Javascript

Choose your learning style9 modes available
Introduction

Promise chaining helps you run tasks one after another in order. It makes sure each step waits for the previous one to finish.

When you need to do several tasks that depend on each other, like loading data then processing it.
When you want to handle multiple asynchronous steps without deeply nested code.
When you want to catch errors from any step in a simple way.
When you want to keep your code clean and easy to read while working with promises.
Syntax
Javascript
const promise = new Promise((resolve, reject) => {
  // do something async
  resolve(value);
});

promise
  .then(result => {
    // handle result
    return nextValue;
  })
  .then(nextResult => {
    // handle next result
  })
  .catch(error => {
    // handle any error from above
  });

Each then returns a new promise, so you can chain many.

If a then returns a value, it becomes the input for the next then.

Examples
This example starts with a resolved promise with value 5, doubles it, then prints 10.
Javascript
Promise.resolve(5)
  .then(value => value * 2)
  .then(value => console.log(value));
This shows how errors in a then are caught by catch.
Javascript
Promise.resolve()
  .then(() => {
    throw new Error('Oops');
  })
  .catch(error => console.log(error.message));
Shows chaining with multiple then calls passing values along.
Javascript
Promise.resolve('start')
  .then(value => {
    console.log(value);
    return 'next';
  })
  .then(value => console.log(value));
Sample Program

This program gets a number asynchronously, then changes it step by step using promise chaining. Each step waits for the previous one.

Javascript
function fetchNumber() {
  return new Promise((resolve) => {
    setTimeout(() => resolve(10), 500);
  });
}

fetchNumber()
  .then(number => {
    console.log('First number:', number);
    return number * 3;
  })
  .then(newNumber => {
    console.log('After multiplying by 3:', newNumber);
    return newNumber - 5;
  })
  .then(finalNumber => {
    console.log('After subtracting 5:', finalNumber);
  })
  .catch(error => {
    console.error('Error:', error);
  });
OutputSuccess
Important Notes

Time complexity depends on the tasks inside each then, but chaining itself is fast.

Space complexity is low since promises handle state internally.

Common mistake: forgetting to return a value inside then causes the next then to get undefined.

Use promise chaining when you want clear, step-by-step async code instead of nested callbacks.

Summary

Promise chaining runs async tasks in order, passing results along.

Each then returns a new promise, allowing many steps.

Errors anywhere in the chain can be caught with a single catch.