Lesson 67 of 296
Sync vs async, and callbacks
What you will learn
- What synchronous and asynchronous code mean
- Why JavaScript needs async code
- What "single-threaded" means
- Callbacks for async work
- Callback hell and error-first callbacks
On this page
Synchronous code
Synchronous (sync) code runs one line at a time, in order. Each line must finish before the next one starts.
console.log("A");
console.log("B");
console.log("C");Always A, B, C.
JavaScript is single-threaded
A thread is a path of execution: one sequence of instructions being run. JavaScript runs your code on one main thread. It can only do one thing at a time.
So if one task takes a long time, everything else waits:
function slowTask() {
const end = Date.now() + 5000;
while (Date.now() < end) {} busy for 5 seconds
}
slowTask();
console.log("Done");In a browser, this freezes the whole page for 5 seconds: no clicks, no scrolling, no animation. This is called blocking the main thread.
Asynchronous code
Many tasks involve waiting, not working: waiting for a server to reply, a file to be read, a timer to finish. Asynchronous (async) code starts the task, does not wait, and continues with the next lines. When the task finishes, a function is called with the result.
console.log("A");
setTimeout(() => {
console.log("B");
}, 1000);
console.log("C");Output:
A
C
B (after 1 second)setTimeout asks the runtime to call the function in 1 second, then JavaScript moves on immediately.
Who does the waiting? Not JavaScript's main thread. The runtime (the browser or Node.js) handles timers, network requests and file reading in the background, then tells JavaScript when they are done. Lesson 68 explains exactly how.
Common async operations
| Operation | Browser | Node.js |
|---|---|---|
| Timers | setTimeout, setInterval | Same |
| Network requests | fetch | fetch, HTTP clients |
| User events | Clicks, key presses | - |
| Files | File inputs | Reading and writing files |
| Databases | - | Database queries |
Callbacks for async work
The original way to handle async results is a callback: a function you pass in, which is called when the work is finished.
function getUser(id, callback) {
setTimeout(() => {
callback({ id, name: "Sam" });
}, 500);
}
getUser(1, (user) => {
console.log(user.name);
});Error-first callbacks (Node.js style)
Older Node.js APIs pass an error as the first argument of the callback, and the result as the second:
fs.readFile("data.txt", "utf8", (err, content) => {
if (err) {
console.error("Could not read file", err);
return;
}
console.log(content);
});If there was no error, err is null.
Callback hell
When each step depends on the previous one, callbacks get nested deeper and deeper:
getUser(1, (user) => {
getOrders(user.id, (orders) => {
getOrderDetails(orders[0].id, (details) => {
getShipping(details.shippingId, (shipping) => {
console.log(shipping.status);
});
});
});
});This is called callback hell or the pyramid of doom. Problems:
- Hard to read.
- Error handling must be repeated at every level.
- Hard to run things in parallel or add timeouts.
Promises (Lesson 69) and async/await (Lesson 70) were created to solve this.
Common mistakes
- Expecting code after an async call to wait for it.
- Trying to
returnan async result from a callback to the outer function. - Running long synchronous work in the browser and freezing the page.
- Forgetting to handle the error argument.
How to say it in an interview
"Synchronous code runs line by line and each line blocks the next. JavaScript is single-threaded, so long synchronous work blocks everything, including the UI. Asynchronous operations like timers, network requests and file reads are handed to the runtime, and JavaScript continues; when they finish, a callback is queued to run. Nested callbacks lead to callback hell, with repeated error handling, which promises and async-await solve."
Key words
| Word | Meaning |
|---|---|
| Synchronous | Runs in order; each step waits for the previous one |
| Asynchronous | Starts a task and continues without waiting for it |
| Thread | A single path of execution |
| Single-threaded | Can only run one piece of code at a time |
| Blocking | A long task that stops everything else from running |
| Callback | A function called when a task finishes |
| Callback hell | Deeply nested callbacks that are hard to manage |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.