JavaScript

Async JavaScript

The event loop, promises, and async/await — the backbone of modern JS.

Async JavaScript

JavaScript is single-threaded but non-blocking. The event loop shuttles work between the call stack, the microtask queue (promise callbacks), and the macrotask queue (timers, I/O).

Promises in one screen

js
const wait = (ms) => new Promise((res) => setTimeout(res, ms));

async function run() {
  console.log("start");
  await wait(200);
  console.log("done");
}

await pauses the async function without blocking the thread. Under the hood it wires a .then onto the awaited promise.

Common pitfalls

  • Forgetting to await — the function returns a floating promise and errors go unhandled.
  • Sequential when parallel would do — use Promise.all for independent work.
  • Mixing callbacks and promises — wrap Node-style callbacks with util.promisify or a manual new Promise.

Interview cheat sheet

ConceptOne-liner
MicrotaskRuns after the current stack, before the next macrotask.
MacrotasksetTimeout, setInterval, I/O callbacks.
Promise.allFails fast on the first rejection.
Promise.allSettledWaits for every promise, never rejects.