Synchronous vs Asynchronous Code

Updated · 8 min read
hardES2026javascriptasynccallbacksnon-blocking

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/await fix it.

Synchronous Code

Synchronous code is simple to read: each line completes before the next starts, and results are available immediately:

sync.js▶ Try it
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");
Output
Start
Total: 250
End

That 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:

blocking.js▶ Try it
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");
Output
Loading...
Loaded 2 payments
Timer wanted to run at 10 ms, ran after 200+ ms

While 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:

non-blocking.js▶ Try it
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");
Output
Loading...
Still responsive: the page can handle clicks now
Loaded 2 payments

Explanation: 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.

BlockingNon-blocking
Code waits for the resultYesNo
Other work during the waitImpossibleContinues
Result deliveredAs the return valueLater, to a callback (or a promise)
Used forFast calculationsNetwork, files, timers, user input

What Runs Asynchronously

OperationBrowserNode.js
Network requestsfetch, WebSocketfetch, node:http
TimerssetTimeout, setIntervalSame, plus setImmediate
User inputEvents (click, input...)n/a
Files and databasesIndexedDB, File APInode:fs/promises, database drivers
Heavy computationWeb WorkersWorker 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:

error-first.js▶ Try it
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);
});
Output
Found Navika
Error: No student 7

Callbacks 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":

callback-hell.js▶ Try it
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}`);
    });
  });
});
Output
Srihitha owes $100
Problem with nested callbacksEffect
Deep nestingHard to read and change
Error handling repeated at every levelEasy to forget one, and errors get lost
try...catch doesn't workThe callback runs later, after the try has finished
No standard shapeEvery library had its own callback conventions
Inversion of controlYou 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:

await-version.js▶ Try it
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);
}
Output
Srihitha owes $100

It 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:

dashboard.js▶ Try it
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;
Output
Dashboard: loading...
Menu and search work while data loads
Dashboard: 3 students, $655 paid

Promise.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
ordered.js▶ Try it
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));
  });
});
Output
first
second
third

Quick check: Sync vs async

3 questions
1Why does JavaScript need asynchronous code?
2In an error-first callback, what is the first argument?
3Why can't try...catch catch errors thrown inside a setTimeout callback?

Key Takeaways

ConceptMeaning
SynchronousRuns to completion before the next line
AsynchronousStarts now, result later
BlockingHolds the thread while waiting
CallbackA function called later with the result
Error-first callback(err, result) => ...

Was this tutorial helpful?

Lesson 101 of 139