Trace a Promise chain the way interviewers do: executor timing, microtask order, what each handler returns, why a missing return hands undefined to the next step, and how chains and async/await replace nested callbacks without solving cancellation on their own.
Frontend interview practice question
Why does my .then() get undefined? Promise chains, async/await, and callback hell
Interview quick answer
Interview focus
This JavaScript interview question tests whether you can explain .then() Gets undefined: Promise Chains Explained, connect it to production trade-offs, and handle common follow-up questions.
- .then() Gets undefined: Promise Chains Explained explanation without falling back to memorized definitions
- Async Await and Concurrency reasoning, edge cases, and production failure modes
- How you would answer the most likely JavaScript interview follow-up
Use this JavaScript interview question to rehearse a quick answer, common mistake, follow-up, and production pitfall.
Full interview answer
The bug to explain
A chain renders undefined even though every request succeeded. The usual cause is one .then() handler that forgot to return: each .then() creates a fresh Promise, and that Promise resolves with whatever the handler returned, so a missing return hands undefined to the next step. The same rule explains why async/await reads like synchronous code: await unwraps exactly that returned value. Below: a worked trace, the chain rules, the callback-hell shape those rules replace, and the production pitfalls that syntax alone does not fix.
console.log('sync start');
Promise.resolve('u42')
.then((id) => {
console.log('then 1', id);
return { id, name: 'Ada' };
})
.then((user) => {
console.log('then 2', user.name);
return user.name; // remove this return and the next handler gets undefined
})
.finally(() => {
console.log('finally cleanup');
})
.then((name) => {
console.log('render', name);
});
console.log('sync end');
// Output:
// sync start
// sync end
// then 1 u42
// then 2 Ada
// finally cleanup
// render Ada
Short version
A Promise represents a future result. async/await is a cleaner way to consume Promises. Same engine behavior, different readability style, but the production pitfall is assuming await is always clearer when it may accidentally serialize independent work. A strong production answer usually shows both independent work started together and one stale-request guard, because syntax is not the hard part.
Question | Answer |
|---|---|
Do async functions return Promises? | Yes, always. |
Does await block the whole app? | No. It pauses only that async function. |
Does await change event-loop priority? | No. Promise continuation still resumes as microtasks. |
function fetchUser(id) {
return Promise.resolve({ id, name: 'Ada' });
}
// Promise style
fetchUser(1)
.then(user => user.name)
.then(name => console.log(name))
.catch(console.error);
// async/await style
async function run() {
try {
const user = await fetchUser(1);
console.log(user.name);
} catch (err) {
console.error(err);
}
}
run();
Most important practical rule: avoid accidental serialization
// ❌ Sequential (slow if independent)
const a = await fetch('/a').then(r => r.json());
const b = await fetch('/b').then(r => r.json());
// ✅ Parallel (faster)
const [a2, b2] = await Promise.all([
fetch('/a').then(r => r.json()),
fetch('/b').then(r => r.json())
]);
Need | Preferred API | Why |
|---|---|---|
All must succeed |
| Fast-fails on first rejection. |
Need every outcome |
| Get success+failure results together. |
First success wins |
| Useful for fallback mirrors/CDNs. |
First settled wins |
| Timeout or first-responder patterns. |
let activeController;
let latestRequestId = 0;
async function loadDashboard(userId) {
activeController?.abort();
const controller = new AbortController();
activeController = controller;
const requestId = ++latestRequestId;
try {
const [profile, notifications] = await Promise.all([
fetch(`/api/profile/${userId}`, { signal: controller.signal }).then(r => r.json()),
fetch(`/api/notifications/${userId}`, { signal: controller.signal }).then(r => r.json())
]);
if (requestId !== latestRequestId) return; // stale result guard
renderDashboard({ profile, notifications });
} catch (err) {
if (err.name === 'AbortError') return;
reportError(err);
}
}
Why this pattern wins in production
Start independent requests together, keep one try/catch boundary, and pair AbortController with a request-identity guard when older work must never overwrite newer UI state.
Promise mechanics under the hood
A Promise is a one-way state machine: pending -> fulfilled or pending -> rejected. The executor runs immediately, callbacks wait as microtasks, and the Promise settles once.
Mechanic | Reality |
|---|---|
Executor timing | Runs immediately when Promise is created. |
then/catch timing | Callbacks run later as microtasks. |
Settlement | First resolve/reject wins; later calls ignored. |
Chaining | Each then returns a fresh Promise. |
console.log('A');
const p = new Promise((resolve) => {
console.log('B executor');
resolve(1);
resolve(2); // ignored
});
p.then(v => console.log('C then:', v));
console.log('D');
// Output: A, B executor, D, C then: 1
Chain propagation rules (must know)
Promise.resolve(10)
.then(v => v + 1) // next gets 11
.then(v => Promise.resolve(v * 2)) // waits, next gets 22
.then(() => { throw new Error('boom'); })
.catch(err => {
console.log(err.message); // boom
return 7; // recovery value
})
.then(v => console.log(v)); // 7
If handler returns... | Next link receives... |
|---|---|
Plain value | Fulfilled Promise with that value. |
Promise/thenable | Resolved/rejected result of that Promise. |
Thrown error | Rejected Promise with that error. |
Likely follow-up confusion
- Promise state and callback scheduling are not the same thing: a Promise can already be fulfilled while your
.then()callback is still waiting as a microtask. finally()runs after settlement, but it does not replace the chain value unless it throws or returns a rejecting Promise.- Each
.then()creates a fresh Promise, so value flow depends on what youreturnorthrow.
Where callbacks fit, and where callback hell starts
A callback is a function you hand to another API so it can decide when to call you. That is still the right model for repeated notifications such as DOM events, observers, and WebSocket messages, because there is no single final value to resolve. It becomes callback hell when one async step owns the next async step and every branch repeats error handling: sequencing becomes implicit, failures get duplicated, and control flow is hard to debug.
getUser(userId, (err, user) => {
if (err) return handleError(err);
getOrders(user.id, (err, orders) => {
if (err) return handleError(err);
getRecommendations(orders, (err, recs) => {
if (err) return handleError(err);
renderDashboard(user, orders, recs);
});
});
});
Problem in callback hell | Why it hurts | Promise-based fix |
|---|---|---|
Pyramid-shaped nesting | Low readability, hard reviews | Flat |
Repeated error checks | Missed error branches, inconsistent behavior | Single terminal |
Hard composition | Sequential/parallel logic becomes messy |
|
Hidden control flow | Difficult debugging and testing | Deterministic chain with explicit returns |
After: one chain, one error boundary
Each step returns a Promise. Data flows forward, and one .catch() handles failures.
getUserP(userId)
.then((user) =>
getOrdersP(user.id).then((orders) => ({ user, orders }))
)
.then(({ user, orders }) =>
getRecommendationsP(orders).then((recs) => ({ user, orders, recs }))
)
.then(({ user, orders, recs }) => {
renderDashboard(user, orders, recs);
})
.catch((err) => {
logError(err);
showFallbackUI();
});
Converting callback APIs safely
Wrap error-first callback APIs once in a small promisify helper and reuse the wrapper, so callback-style code stays at the boundary and the rest of the flow moves into chains.
function promisify1(fn) {
return (...args) =>
new Promise((resolve, reject) => {
fn(...args, (err, value) => {
if (err) reject(err);
else resolve(value);
});
});
}
const readFileP = promisify1(readFile);
Common migration mistakes
- Wrapping everything in Promises but still nesting deeply.
- Forgetting to
returninside.then()(breaks the chain). - Mixing callback and Promise style in the same function without clear boundaries.
- Catching errors too early and swallowing diagnostic context.
- Assuming Promises solve cancellation automatically.
saveDraftP(data)
.then((result) => {
auditP(result.id); // missing return -> chain no longer waits for audit
})
.then(() => showSuccess())
.catch(reportError);
Pattern | What it means | Why it matters |
|---|---|---|
Event callback | Runs every time the source emits a new event. | Great for DOM events, observers, and repeated notifications. |
Error-first callback | First argument represents failure, second carries data. | Common in legacy Node-style APIs and old libraries. |
Callback hell | Nested callbacks own each next step. | Makes sequencing, cancellation, and testing harder. |
Practical scenario
Autocomplete requests fire on each keystroke. You debounce input, cancel stale requests, and only render the latest resolved result to avoid flicker and race bugs.
Common pitfalls
- Using
awaitinside loops when calls are independent. - Forgetting terminal error handling.
- Assuming Promise cancellation exists automatically.
Still so complicated?
Promise is the contract for future data. await is just cleaner punctuation when reading that contract.
Summary
- Promises and async/await are the same async model.
- Use try/catch (or .catch) consistently.
- Parallelize independent work with
Promise.all. - Use cancellation for stale UI requests.
Use this as one explanation rep, then continue with the JavaScript interview questions cluster or a guided prep path.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.