What will be the output? (Promise Chaining)
This problem demonstrates Promise chaining and how each .then() waits for the previous promise to resolve.
Quick Navigation: Promise Chaining Execution • Sequential vs Parallel Execution • Return Values in .then()
Promise Chaining Execution
Promise chaining allows you to execute asynchronous operations sequentially. Each .then() waits for the previous promise to resolve before executing.
Execution Flow
const promise1 = new Promise(resolve => setTimeout(() => resolve('apple'), 100));
const promise2 = new Promise(resolve => setTimeout(() => resolve('banana'), 200));
const promise3 = new Promise(resolve => setTimeout(() => resolve('orange'), 300));
promise1
.then(result => {
console.log(result); // 1️⃣ After 100ms: "apple"
return promise2; // Returns promise2 (not its value yet)
})
.then(result => {
console.log(result); // 2️⃣ After 200ms more: "banana"
return promise3; // Returns promise3
})
.then(result => {
console.log(result); // 3️⃣ After 300ms more: "orange"
console.log('All promises resolved successfully!');
})Key Points
1. promise1 resolves after 100ms → logs "apple"
2. promise2 is returned and starts executing (already started, but chain waits)
3. After total 300ms (100ms + 200ms), promise2 resolves → logs "banana"
4. promise3 is returned
5. After total 600ms (300ms + 300ms), promise3 resolves → logs "orange"
6. Final message is logged
Output:
apple
banana
orange
All promises resolved successfully!Total Time: ~600ms (sequential, not parallel)
Sequential vs Parallel Execution
Sequential (Chaining)
promise1
.then(() => promise2) // Waits for promise1, then promise2
.then(() => promise3); // Waits for promise2, then promise3
// Total: 100ms + 200ms + 300ms = 600msParallel (Promise.all)
Promise.all([promise1, promise2, promise3])
.then(results => {
console.log(results); // ['apple', 'banana', 'orange']
});
// Total: max(100ms, 200ms, 300ms) = 300msWhen to Use Each
Sequential (Chaining):
Parallel (Promise.all):
Return Values in .then()
Returning a Value
Promise.resolve(1)
.then(value => {
return value * 2; // Returns 2
})
.then(value => {
console.log(value); // 2
});Returning a Promise
Promise.resolve(1)
.then(value => {
return Promise.resolve(value * 2); // Returns a promise
})
.then(value => {
console.log(value); // 2 (waits for promise to resolve)
});Key: When you return a promise, the next .then() waits for that promise to resolve and receives its resolved value.
Not Returning (Undefined)
Promise.resolve(1)
.then(value => {
console.log(value); // 1
// No return statement
})
.then(value => {
console.log(value); // undefined
});If you don't return anything, the next .then() receives undefined.