Promise chaining helps you run tasks one after another in order. It makes sure each step waits for the previous one to finish.
Promise chaining in 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.
Promise.resolve(5) .then(value => value * 2) .then(value => console.log(value));
then are caught by catch.Promise.resolve() .then(() => { throw new Error('Oops'); }) .catch(error => console.log(error.message));
then calls passing values along.Promise.resolve('start') .then(value => { console.log(value); return 'next'; }) .then(value => console.log(value));
This program gets a number asynchronously, then changes it step by step using promise chaining. Each step waits for the previous one.
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); });
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.
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.