1. The Single-Threaded Event Loop
The JavaScript runtime consists of a Call Stack, Web APIs (provided by the browser/Node.js), a Microtask Queue (Promises, queueMicrotask), and a Macrotask Queue (setTimeout, setInterval, I/O).
Master asynchronous JavaScript: Event Loop, Microtask vs Macrotask queues, Promise chaining, async/await syntax, and error handling.
Format: PDF Document • Size: 5.7 KB • Pages: 2
JavaScript is single-threaded, meaning it can only execute one command at a time. Yet it powers real-time chat, streaming media, and high-frequency API requests without freezing the user interface. It achieves this concurrency through the Event Loop and Asynchronous APIs.
The JavaScript runtime consists of a Call Stack, Web APIs (provided by the browser/Node.js), a Microtask Queue (Promises, queueMicrotask), and a Macrotask Queue (setTimeout, setInterval, I/O).
Async/await is syntactic sugar over native Promises, turning nested .then() callback chains into readable synchronous-looking code.
1234567891011121314151617181920212223async function fetchLearningNotes(category: string, signal?: AbortSignal) {try {const response = await fetch(`/api/notes?category=${encodeURIComponent(category)}`, {method: "GET",headers: { "Accept": "application/json" },signal, // Enables cancellation if component unmounts});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const data = await response.json();return { success: true, notes: data.notes };} catch (error: any) {if (error.name === "AbortError") {console.log("Fetch request aborted.");return { success: false, aborted: true };}console.error("Failed to fetch notes:", error.message);return { success: false, error: error.message };}}
Avoid waterfall requests where independent calls wait for each other unnecessarily:
123456789// SLOW WATERFALL (Total time = 300ms + 400ms = 700ms)const user = await fetchUser();const notes = await fetchNotes();// FAST PARALLEL (Total time = max(300ms, 400ms) = 400ms)const [user, notes] = await Promise.all([fetchUser(),fetchNotes(),]);
fetch() only rejects when a network failure occurs (e.g. offline, DNS failure, CORS block). An HTTP 404 or 500 is considered a successful HTTP transaction with error status.
Reinforce what you just learned with interactive challenges.
In what order will the numbers 1, 2, 3, 4 log to the console?
console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4);