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.allfor independent work. - Mixing callbacks and promises — wrap Node-style callbacks with
util.promisifyor a manualnew Promise.
Interview cheat sheet
| Concept | One-liner |
|---|---|
| Microtask | Runs after the current stack, before the next macrotask. |
| Macrotask | setTimeout, setInterval, I/O callbacks. |
Promise.all | Fails fast on the first rejection. |
Promise.allSettled | Waits for every promise, never rejects. |
