The Secret Life of JavaScript: Asynchrony in Detail
JavaScript looks synchronous but behaves asynchronously behind the scenes. Understanding this secret life is essential for writing reliable and high-performance applications.
JavaScript Is Single-Threaded
JavaScript runs on one thread and executes one task at a time using a call stack.
console.log("A");
console.log("B");
console.log("C");
The Problem with Blocking Code
Blocking code freezes the browser and must be avoided.
function blockFor5Seconds() {
const end = Date.now() + 5000;
while (Date.now() < end) {}
}
The JavaScript Runtime
- Call Stack
- Web APIs
- Callback Queue
- Microtask Queue
- Event Loop
Web APIs and setTimeout
setTimeout(() => {
console.log("Hello");
}, 2000);
Microtasks vs Callbacks
Promise.resolve().then(() => console.log("Promise"));
setTimeout(() => console.log("Timeout"), 0);
Async/Await
async function loadData() {
try {
const data = await fetchData();
console.log(data);
} catch (err) {
console.error(err);
}
}
Parallel Execution
await Promise.all([
fetchUser(),
fetchOrders()
]);
Conclusion
Understanding the Event Loop unlocks the true power of JavaScript asynchrony.
