Synchronous vs Asynchronous Code
Synchronous code runs one statement after another, each finishing before the next starts. Asynchronous code starts an operation now and handles its result later, letting other code run in between. JavaScript needs asynchronous code because it runs your program on a single main thread: if it simply waited for a network request or a timer, the whole page (or server) would freeze until the wait was over. This lesson explains the problem, the original solution (callbacks), and why callbacks led to promises and async/await, the subject of the rest of this chapter.
In One Minute
- JavaScript runs your code on one thread: one thing at a time.
- Slow operations (network, disk, timers, user input) are handled by the runtime in the background; your code is told when they finish.
- Blocking code makes everything wait; non-blocking code starts work and continues immediately.
- The original way to receive a later result is a callback function.
- Nesting callbacks leads to "callback hell"; promises and
async/awaitfix it.
Synchronous Code
Synchronous code is simple to read: each line completes before the next starts, and results are available immediately:
function total(fees) {
return fees.reduce((sum, f) => sum + f, 0);
}
console.log("Start");
const sum = total([120, 85, 45]);
console.log("Total:", sum);
console.log("End");Start
Total: 250
EndThat works perfectly for calculations that take microseconds. The trouble starts when an operation takes a long time.
The Problem: Waiting Blocks Everything
Suppose loading payments from a server took one second and JavaScript simply waited for it. Here is what waiting does to a single thread, simulated with a busy loop:
function loadPaymentsBlocking() {
const until = Date.now() + 200;
while (Date.now() < until) {
// waiting... nothing else can run on this thread
}
return [120, 85];
}
const started = Date.now();
setTimeout(() => console.log(`Timer wanted to run at 10 ms, ran after ${Date.now() - started >= 200 ? "200+" : "<200"} ms`), 10);
console.log("Loading...");
const payments = loadPaymentsBlocking();
console.log("Loaded", payments.length, "payments");Loading...
Loaded 2 payments
Timer wanted to run at 10 ms, ran after 200+ msWhile the loop waited, the timer couldn't fire. In a browser, clicks, typing, scrolling and animations would all freeze too; on a server, every other user's request would wait. One thread, blocked, means everything stops.
Non-Blocking: Start Now, Finish Later
The fix is to not wait. You ask the runtime to do the slow part, give it a function to call when it's done, and carry on. The runtime (the browser, or Node.js) does the waiting outside your JavaScript code:
function loadPayments(callback) {
setTimeout(() => callback([120, 85]), 50);
}
console.log("Loading...");
loadPayments((payments) => {
console.log("Loaded", payments.length, "payments");
});
console.log("Still responsive: the page can handle clicks now");Loading...
Still responsive: the page can handle clicks now
Loaded 2 paymentsExplanation: loadPayments starts a timer (standing in for a network request) and returns at once. The last line runs immediately. Fifty milliseconds later, the runtime calls the callback with the data. During those 50 ms, the thread was free for anything else.
| Blocking | Non-blocking | |
|---|---|---|
| Code waits for the result | Yes | No |
| Other work during the wait | Impossible | Continues |
| Result delivered | As the return value | Later, to a callback (or a promise) |
| Used for | Fast calculations | Network, files, timers, user input |
What Runs Asynchronously
| Operation | Browser | Node.js |
|---|---|---|
| Network requests | fetch, WebSocket | fetch, node:http |
| Timers | setTimeout, setInterval | Same, plus setImmediate |
| User input | Events (click, input...) | n/a |
| Files and databases | IndexedDB, File API | node:fs/promises, database drivers |
| Heavy computation | Web Workers | Worker threads |
The JavaScript language itself has no I/O at all; every asynchronous operation comes from the runtime. The event loop (next lesson) is how the runtime hands completed work back to your code, one piece at a time.
Callbacks
A callback is a function you pass so it can be called later with the result. Node.js built its early APIs on error-first callbacks: the callback's first argument is an error (or null), and the result comes second:
function getStudent(id, callback) {
setTimeout(() => {
if (id !== 1) return callback(new Error(`No student ${id}`));
callback(null, { id: 1, name: "Navika", balance: 120 });
}, 10);
}
getStudent(1, (err, student) => {
if (err) return console.log("Error:", err.message);
console.log("Found", student.name);
});
getStudent(7, (err, student) => {
if (err) return console.log("Error:", err.message);
console.log("Found", student.name);
});Found Navika
Error: No student 7Callbacks work, but they have real problems once operations depend on each other.
Callback Hell
When each step needs the previous step's result, callbacks nest inside callbacks, drifting right across the screen. This is nicknamed callback hell or the "pyramid of doom":
const db = {
getStudent: (id, cb) => setTimeout(() => cb(null, { id, name: "Srihitha" }), 5),
getPayments: (student, cb) => setTimeout(() => cb(null, [200, 150]), 5),
getFee: (student, cb) => setTimeout(() => cb(null, 450), 5),
};
db.getStudent(2, (err, student) => {
if (err) return console.log(err.message);
db.getPayments(student, (err, payments) => {
if (err) return console.log(err.message);
db.getFee(student, (err, fee) => {
if (err) return console.log(err.message);
const paid = payments.reduce((a, b) => a + b, 0);
console.log(`${student.name} owes $${fee - paid}`);
});
});
});Srihitha owes $100| Problem with nested callbacks | Effect |
|---|---|
| Deep nesting | Hard to read and change |
| Error handling repeated at every level | Easy to forget one, and errors get lost |
try...catch doesn't work | The callback runs later, after the try has finished |
| No standard shape | Every library had its own callback conventions |
| Inversion of control | You trust the library to call your callback exactly once; buggy code might call it twice or never |
The Same Flow with async/await
Promises (an object representing a future result) and async/await (syntax for waiting on promises without blocking) solve these problems. Here is the same logic, rewritten; the next lessons explain every piece:
const db = {
getStudent: async (id) => ({ id, name: "Srihitha" }),
getPayments: async () => [200, 150],
getFee: async () => 450,
};
try {
const student = await db.getStudent(2);
const payments = await db.getPayments(student);
const fee = await db.getFee(student);
const paid = payments.reduce((a, b) => a + b, 0);
console.log(`${student.name} owes $${fee - paid}`);
} catch (err) {
console.log(err.message);
}Srihitha owes $100It reads top to bottom like synchronous code, uses one ordinary try...catch for every step, and still never blocks the thread: each await lets other work run while waiting.
In Practice
The Fee Tracker's dashboard needs three things from the server. A naive version would block or nest callbacks; the async version starts the work, keeps the page responsive, and shows the result when it arrives:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const api = {
students: () => wait(30, ["Navika", "Srihitha", "Advitha"]),
totalPaid: () => wait(20, 655),
};
console.log("Dashboard: loading...");
const load = (async () => {
const [students, total] = await Promise.all([api.students(), api.totalPaid()]);
console.log(`Dashboard: ${students.length} students, $${total} paid`);
})();
console.log("Menu and search work while data loads");
await load;Dashboard: loading...
Menu and search work while data loads
Dashboard: 3 students, $655 paidPromise.all starts both requests at once and waits for both, covered in the lesson on running tasks in parallel.
Common Mistakes
Expecting an async result on the next line. const data = loadPayments(cb); console.log(data) logs undefined; the result arrives later, in the callback.
Blocking with busy loops or synchronous APIs. Long loops and APIs like synchronous XHR freeze the page. Use asynchronous APIs.
Wrapping callback code in try...catch. Errors inside the callback escape it. Handle errors in the callback, or use promises.
Calling a callback more than once. In code you write that takes callbacks, make sure every path calls it exactly once (or return after calling it).
Practice
Challenge: Write delay(ms, value, callback) that calls callback(value) after ms milliseconds, then use it to log "first", "second", "third" in that order even though they're scheduled with delays 30, 10 and 20, by nesting appropriately.
Show solution
function delay(ms, value, callback) {
setTimeout(() => callback(value), ms);
}
delay(30, "first", (a) => {
console.log(a);
delay(10, "second", (b) => {
console.log(b);
delay(20, "third", (c) => console.log(c));
});
});first
second
thirdKey Takeaways
| Concept | Meaning |
|---|---|
| Synchronous | Runs to completion before the next line |
| Asynchronous | Starts now, result later |
| Blocking | Holds the thread while waiting |
| Callback | A function called later with the result |
| Error-first callback | (err, result) => ... |
Was this tutorial helpful?