Interview Questions 4
Async puzzles.
Async questions are very common in JavaScript interviews. Usually it's a puzzle about the order of output, or writing a small async helper. Let's do one of each.

- Async is a favourite
- Order-of-output puzzles
- Write a helper
What order?
Normal code runs first, so A, then E. Inside the async function, everything before the first await runs straight away, so B appears before E. The promise callbacks, C and D, run next, in the microtask queue. And the timer, F, runs last. Run it.
console.log("A");
setTimeout(() => console.log("F"), 0);
async function task() {
console.log("B");
await null;
console.log("C");
}
task();
Promise.resolve().then(() => console.log("D"));
console.log("E");A B E C D F
Retry
A favourite helper is retry. It calls an async function, and if it fails, tries again, up to a limit, waiting a little longer each time. Our flaky function fails twice, then succeeds, so retry gets the answer on the third attempt. Run it.
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
async function retry(fn, attempts = 3) {
for (let i = 1; i <= attempts; i++) {
try { return await fn(); }
catch (e) {
console.log(`Attempt ${i} failed: ${e.message}`);
if (i === attempts) throw e;
await sleep(100 * i);
}
}
}
let tries = 0;
const flaky = async () => { if (++tries < 3) throw new Error("busy"); return "data!"; };
console.log("Result:", await retry(flaky));Attempt 1 failed: busy Attempt 2 failed: busy Result: data!
Summary
For order puzzles, think: normal code, then microtasks, then timers. For helpers like retry, combine loops, try and catch, and await. Next, a cheat sheet of the whole course.
Key takeaways- Sync, micro, timers
- await splits a function
- retry with backoff