Callbacks

Synchronous vs Asynchronous

Example

JavaScript runs one thing at a time. Slow tasks (timers, network, files) are started and finished later, so the rest of the code does not wait:

console.log("1. Order placed");
setTimeout(() => console.log("3. Food delivered"), 50);
console.log("2. Continue browsing");

Output

1. Order placed
2. Continue browsing
3. Food delivered

Example

A callback is a function passed to another function, to be called when the work is done:

function fetchUser(id, callback) {
  setTimeout(() => callback({ id, name: "Asha" }), 30);
}
fetchUser(7, (user) => {
  console.log("Got user:", user.name);
});

Output

Got user: Asha

Callback Hell

When each step depends on the previous one, callbacks nest deeper and deeper, and error handling must be repeated at every level:

getUser(id, (user) => {
  getOrders(user, (orders) => {
    getDetails(orders[0], (details) => {
      getInvoice(details, (invoice) => {
        // ... the "pyramid of doom"
      });
    });
  });
});

Promises and async/await solve this.