Section 1: How async JavaScript works
Why JavaScript needs async code
JavaScript in a browser runs your code on a single main thread. That thread also handles user input, layout and painting. If your code takes two seconds to finish, the page cannot respond to clicks or scroll for those two seconds.
Many operations are slow compared with running code: network requests, reading files, timers, database queries. If JavaScript waited for each of these to finish before doing anything else, every app would freeze constantly. Instead, it starts the operation, carries on with other work and handles the result later, when it arrives.
A first example
console.log("1: before");
setTimeout(() => console.log("2: timer"), 0);
console.log("3: after");
The output is 1, 3, 2, even though the timer delay is zero. setTimeout does not pause the code. It asks the environment to run the callback later, and the rest of the script continues. The callback can only run once the current code has finished.
Who does the waiting
JavaScript itself does not wait for the network. The host environment, the browser or Node.js, provides APIs such as timers, fetch and file access. These run outside your JavaScript code, and when they finish, they schedule your callback to run. Your code is never interrupted in the middle; callbacks always run when the main thread is free.
Three styles you will meet
- Callbacks: pass a function that is called when the work is done. Common in older APIs and Node.js core modules.
- Promises: an object representing a value that will be available later, with methods to react to success or failure.
- async and await: syntax built on promises that lets asynchronous code read like ordinary step by step code.
Modern code mostly uses async and await, but it is built on promises, and promises are scheduled by the event loop. Understanding the layers underneath is what lets you debug async problems instead of guessing.
What this means in practice
Async code makes ordering less obvious. When results arrive later, you must think about what happens if they arrive late, out of order, or never. Most async bugs are about one of these three cases, and we will tackle each of them in this course.