Lesson 72 +15 XP

Callbacks

Callbacks

A callback is a function passed to another function and run later, usually when an async task finishes.

The idea

setTimeout(function() {
  console.log("Timer done!");
}, 1000);

The anonymous function is a callback that runs when the timer finishes.

A custom async function

function loadData(callback) {
  setTimeout(function() {
    const data = { user: "Ada" };
    callback(data); // hand the data to the callback
  }, 1000);
}

loadData(function(data) {
  console.log(data.user); // "Ada" after 1 second
});

Why callbacks?

  • They let you say "run this when the work is done".
  • They keep code from blocking the page.
  • They were the original way to handle async in JavaScript.

Callback hell

Nesting many callbacks gets hard to read:

getA(function(a) {
  getB(a, function(b) {
    getC(b, function(c) {
      // deeply nested...
    });
  });
});

This is why Promises and async/await were created.

TL;DR

  • A callback runs later, after a task finishes.
  • Callbacks are the basic async pattern.
  • Deep nesting is called callback hell.
  • Promises and async/await improve on callbacks.