Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 133 ยท Asynchronous Programming

Callbacks and Error-First Style

Understand Node.js callbacks and the error-first convention, escape callback hell, avoid the sync-or-async trap, and convert callback APIs with util.promisify and callbackify.

A callback is a function you hand to another function so it can "call you back" later, when something has finished. In a language where the main thread must never sit idle waiting for a disk or a network, that idea is the foundation of everything. Node.js was built around it: its first ten years of APIs, from fs.readFile to http.get, all take a callback as the last argument.

Today you will mostly write async/await code (see async/await Patterns), but callbacks have not gone away. They live inside older libraries, inside event emitters, inside streams, and underneath every promise. Reading and writing them fluently, and knowing their traps, is part of knowing Node.

What a callback is

Passing a function is nothing special in JavaScript; functions are values. A callback becomes asynchronous when the function that receives it does not call it right away, but later, after some work completes. In the example below, setTimeout stores the callback and Node runs it when the timer is due, after the rest of the script has finished.

Node.js Synchronous and asynchronous callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

forEach calls its callback three times before returning, so those lines print first. The timer callback prints last, even though it was registered earlier than the final console.log. When people say "callback", they usually mean the asynchronous kind, and that is the kind this lesson is about.

The error-first convention

Asynchronous code cannot use try/catch the way synchronous code does (you will see why in a moment), so Node settled on a small, strict convention that every core API follows:

  1. The callback is the last argument.
  2. The callback's first parameter is the error: null (or undefined) on success, an Error object on failure.
  3. The following parameters carry the results.
TEXT
function callback(err, result1, result2, ...) { ... }

That is why it is called error-first (or "Node-style", or "errback"). You must check err before touching the results. Here it is with a real core API; reading a file that does not exist fails, and the error tells you exactly why:

Node.js Reading a file with an error-first callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the return after handling the error. Without it the function would carry on and use a text that does not exist. Forgetting that return is one of the most common callback bugs.

The two reads run concurrently: Node starts both, then calls back in whichever order they finish. Here the failed lookup is quick, so it prints first. Never assume an order between independent callbacks unless you made one.

Writing your own error-first function

The convention is easy to follow in your own code. Take the callback last, and call it exactly once, with the error first.

Node.js A function with an error-first callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two rules that keep callbacks sane: call the callback exactly once, and never both an error and a result. A function that can call back twice (for example once from an error path and again from a success path after a missing return) will run your code twice and produce bugs that are hard to reproduce.

Why try/catch does not work

try/catch only catches errors thrown while the try block is on the call stack. An asynchronous callback runs later, from a fresh call stack, so by then the try block is long gone. That is exactly why errors are passed as arguments instead of thrown.

Node.js try/catch cannot catch a later throw (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The try block finishes happily. Ten milliseconds later the callback throws on a new stack, nothing is there to catch it, and Node prints Error: thrown inside a timer callback with a stack trace that starts at Timeout._onTimeout (main.mjs:3:11) (notice that no line of your code from the try block appears in it), then exits with code 1 (an uncaught exception, as you will see in Errors and Error Handling). The fix is to handle problems inside the callback, or to pass them on with the error-first convention.

An exception thrown inside a callback that you passed to somebody else's function usually crashes the process. Wrap risky code inside the callback with its own try/catch, and report failures through callback(err) instead of throwing.

Callback hell and how to flatten it

Real tasks need several asynchronous steps in order: look up a user, load their orders, load the items of the first order. With callbacks every step nests inside the previous one, and the code drifts to the right in what is famously called the pyramid of doom or callback hell.

Node.js Nested callbacks (the pyramid)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

It works, but each level repeats the same if (err) boilerplate, variables from outer levels leak inward, and adding a fourth step pushes the code further right. There are two classic ways out, and a modern one.

1. Name the steps. Turn each anonymous callback into a named function at the top level. The code reads top to bottom again.

Node.js Flattening with named functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

2. Use promises. Turn the callback API into one that returns a promise (next section) and write the same flow with await, which gives you a straight line and ordinary try/catch. This is what almost all modern Node code does; see Promises in Depth.

Converting with util.promisify and callbackify

util.promisify(fn) takes any function that follows the error-first convention and returns a function that returns a promise. If the callback receives an error, the promise rejects; otherwise it resolves with the first result. Many core modules also ship a ready-made promise version (fs/promises, timers/promises), which you should prefer when it exists.

Node.js util.promisify and util.callbackify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

promisify only works for callbacks with the exact (err, value) shape. A function that calls back with several results (cb(null, a, b)) loses the extras unless it defines util.promisify.custom, which is how setTimeout offers a promise form. A function that does not follow error-first (for example fs.exists(path, cb), whose only argument is a boolean) cannot be promisified correctly; wrap it by hand with new Promise.

The sync-or-async trap

A function that calls its callback synchronously in some cases and asynchronously in others is nicknamed "releasing Zalgo", and it causes real bugs. Callers cannot know whether the code after the call has already run or not.

Node.js A callback that is sometimes sync, sometimes async

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For the cached key, the bad version prints before > callback > after, but for the missing key before > after > callback. The caller's code behaves differently depending on data. The good version always delivers the callback after the current code finishes. The rule: a function should be either always synchronous or always asynchronous. When you must defer, use process.nextTick or queueMicrotask (see The Event Loop) rather than a timer, so the delay stays tiny.

Other callback habits worth knowing

  • Callbacks last, error first. Keep the shape predictable so tools like promisify work.
  • Don't swallow errors. if (err) return; hides the failure. At least log it or pass it up.
  • Use return callback(err) (or if/else) to avoid running the success code after an error.
  • Events are not error-first. An EventEmitter listener has no err parameter; errors arrive through a separate 'error' event (see Events).
  • Bind or capture this deliberately. Arrow functions keep the outer this; regular functions get whatever the caller sets.
  • Beware loops. Starting 10,000 file reads in a loop with callbacks starts them all at once; use a limit (see Concurrency Control and Queues).

Callbacks are still the right tool when the callback may run many times (event handlers, stream.on('data'), server.on('request')) or when you need the lowest overhead. A promise settles only once, so it can only model "one result later".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the error-first convention, what is the first argument of the callback?

    The first parameter is the error (null or undefined on success), and the results follow it.
  2. 2. Why can't a try/catch block around setTimeout catch an error thrown in its callback?

    The error is thrown after the surrounding try block has already completed, so nothing is there to catch it. That is why errors are passed as arguments.
  3. 3. What is wrong with a function that calls its callback synchronously on a cache hit and asynchronously otherwise?

    Mixing sync and async delivery makes ordering depend on data. Always deliver the callback asynchronously (for example with process.nextTick) or always synchronously.
  4. 4. What does util.promisify do?

    promisify wraps a function that takes an (err, value) callback so it returns a promise that rejects on err and resolves with the value.
  5. 5. Which line is the most common bug in callback code?

    Without return (or an else branch), execution continues after the error check and uses results that do not exist.

Summary

  • A callback is a function passed to be called later; the asynchronous kind runs from the event loop.
  • Node's convention: callback last, err first, call it exactly once.
  • try/catch cannot catch errors thrown in later callbacks, so report failures with callback(err).
  • Flatten callback pyramids with named functions, or better, switch to promises and await.
  • util.promisify and util.callbackify convert between callback and promise styles.
  • A function must be always sync or always async; use process.nextTick to defer safely.
  • Callbacks remain right for things that happen many times, like events.

Next: Promises in Depth