AI Hints
Home›JavaScript Tutorial›Async Interview and Review
JavaScript · Lesson 133 of 138

Interview Questions 4

Async puzzles.

⏱ 2 min read▶ Video at 2:39:24🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Interview Questions 4
From the video: Interview Questions 4
  • 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.

app.jsjavascript
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");
Output
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.

app.mjsjavascript
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));
Output
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
Next up: Cheat Sheet — the whole course