← Back to Node.js Course | Chapter 4: Async Programming | Lesson 1 of 7

Callbacks

A callback is a function you hand to another function to be called later when the work is done.

In this page:

  1. Callbacks
Syntax
javascript
function functionName(args, callback) {
  // do work
  callback(err, result);
}

functionName(args, (err, result) => {
  if (err) return handleError(err);
  // use result
});

Callbacks

Node's classic style is error-first callbacks: the first argument is an error or null, followed by results. Deep nesting of callbacks leads to hard-to-read callback hell, which promises and async/await solve.

Note: Always check the err argument first.

Example: Callbacks

javascript
function getUser(id, cb) {
  setTimeout(() => {
    if (id <= 0) return cb(new Error("bad id"));
    cb(null, { id, name: "Ada" });
  }, 5);
}
getUser(1, (err, user) => console.log(err ? err.message : user));
getUser(0, (err, user) => console.log(err ? err.message : user));

// Output:
// { id: 1, name: 'Ada' }
// bad id

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Ignoring the error argument
  2. Calling a callback twice
  3. Throwing inside async callbacks and crashing the process
Chapter Summary
  • Callbacks run when work completes
  • Error-first convention
  • Nesting causes callback hell
  • Always handle err
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.