Performance: Promise chaining
Promise chaining affects the responsiveness and smoothness of asynchronous operations in the browser or Node.js event loop.
Jump into concepts and practice - no test required
doTask1()
.then(() => doTask2())
.then(() => doTask3())
.then(() => {
console.log('All done');
});doTask1().then(() => {
return doTask2().then(() => {
return doTask3().then(() => {
console.log('All done');
});
});
});| Pattern | Microtask Queue Complexity | Event Loop Blocking | Error Handling | Verdict |
|---|---|---|---|---|
| Nested .then callbacks | High (deep nesting) | Higher blocking due to nested microtasks | Harder to catch errors | [X] Bad |
| Flat promise chaining | Low (linear chain) | Minimal blocking, smoother event loop | Simpler error propagation | [OK] Good |
promise chaining in Node.js?.then() ensures order, not parallel or immediate stop.promise1 and promise2?.then().then() method expects a function to call when the promise resolves.promise2(). Options A and B call promise2() immediately or pass wrong types. promise1.then.then(promise2) has invalid chaining syntax.Promise.resolve(5)
.then(x => x + 1)
.then(x => { throw new Error('Fail'); })
.catch(err => 'Caught: ' + err.message)
.then(x => console.log(x));then adds 1 to 5, resulting in 6. The second then throws an error.catch catches the error and returns the string 'Caught: Fail'. The last then logs this string.fetchData() .then(data => processData(data)) .then(result => console.log(result)) .catch(console.error())
console.error() calls the function immediately, passing its result (undefined) instead..catch(console.error) without parentheses to pass the function itself.function step1() { return Promise.resolve(2); }
function step2(x) { return Promise.resolve(x * 3); }
function step3(x) { return x + 4; }step1() .then(x => step2(x)) .then(x => step3(x)) .then(console.log);
step1() resolves to 2. Then step2(2) resolves to 6 (2*3).step3(6) returns 10 (6+4) synchronously. Since then accepts a value or promise, it passes 10 to next then which logs 10.