What if you could write complex step-by-step tasks without getting lost in a maze of callbacks?
Why Promise chaining in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you need to perform several tasks one after another, like ordering food, then paying for it, then leaving a tip, all by calling separate functions manually.
Doing each task manually with callbacks or separate steps quickly becomes messy and confusing. It's easy to forget the order, handle errors poorly, or write repetitive code.
Promise chaining lets you link tasks so each one starts only after the previous finishes, keeping your code clean and easy to follow.
orderFood(function(food) {
payForFood(food, function(receipt) {
leaveTip(receipt, function() {
console.log('All done!');
});
});
});orderFood()
.then(payForFood)
.then(leaveTip)
.then(() => console.log('All done!'))
.catch(error => console.error(error));It enables writing clear, readable sequences of asynchronous tasks that handle success and errors smoothly.
Like booking a flight online: first select a flight, then pay, then get a confirmation email--all steps happen one after another without confusion.
Manual callbacks get messy and hard to manage.
Promise chaining links tasks in a clean, readable way.
It helps handle errors and results smoothly in sequence.
Practice
promise chaining in Node.js?Solution
Step 1: Understand asynchronous task execution
Promise chaining allows tasks to run one after another, waiting for each to finish.Step 2: Identify the purpose of chaining
Chaining with.then()ensures order, not parallel or immediate stop.Final Answer:
To run asynchronous tasks one after another in order -> Option CQuick Check:
Promise chaining = ordered async tasks [OK]
- Thinking promises run in parallel by default
- Confusing chaining with synchronous loops
- Believing chaining stops tasks immediately
promise1 and promise2?Solution
Step 1: Understand how to pass functions to
The.then().then()method expects a function to call when the promise resolves.Step 2: Check each option's syntax
promise1.then(() => promise2()) correctly passes a function that callspromise2(). Options A and B callpromise2()immediately or pass wrong types. promise1.then.then(promise2) has invalid chaining syntax.Final Answer:
promise1.then(() => promise2()) -> Option DQuick Check:
Pass a function to then() = promise1.then(() => promise2()) [OK]
- Calling the next promise immediately inside then()
- Using double then without parentheses
- Passing promise instead of function to then()
Promise.resolve(5)
.then(x => x + 1)
.then(x => { throw new Error('Fail'); })
.catch(err => 'Caught: ' + err.message)
.then(x => console.log(x));Solution
Step 1: Follow the promise chain step-by-step
The firstthenadds 1 to 5, resulting in 6. The secondthenthrows an error.Step 2: Understand error handling and final output
Thecatchcatches the error and returns the string 'Caught: Fail'. The lastthenlogs this string.Final Answer:
Caught: Fail -> Option AQuick Check:
Error caught and message logged = Caught: Fail [OK]
- Expecting error to stop all logging
- Thinking catch returns undefined
- Ignoring that catch returns a value to next then
fetchData() .then(data => processData(data)) .then(result => console.log(result)) .catch(console.error())
Solution
Step 1: Check the catch usage
The catch method expects a function reference, butconsole.error()calls the function immediately, passing its result (undefined) instead.Step 2: Correct catch usage
It should be.catch(console.error)without parentheses to pass the function itself.Final Answer:
Incorrect use of catch with immediate function call -> Option BQuick Check:
Pass function to catch, not call it immediately [OK]
- Calling catch handler immediately instead of passing function
- Forgetting to return promises inside then
- Misplacing console.log inside catch
function step1() { return Promise.resolve(2); }
function step2(x) { return Promise.resolve(x * 3); }
function step3(x) { return x + 4; }What will this code log?
step1() .then(x => step2(x)) .then(x => step3(x)) .then(console.log);
Solution
Step 1: Calculate step1 and step2 results
step1()resolves to 2. Thenstep2(2)resolves to 6 (2*3).Step 2: Understand step3 return and final log
step3(6)returns 10 (6+4) synchronously. Sincethenaccepts a value or promise, it passes 10 to nextthenwhich logs 10.Final Answer:
10 -> Option AQuick Check:
Sync return in then passes value = 10 [OK]
- Expecting step3 to return a Promise always
- Thinking console.log logs a Promise object
- Confusing synchronous return with Promise return
