Callbacks: passing code to be run later

A callback is a function handed to another function so that the other function can call it. The name says what the idea is for: the caller passes the code to run, and the callee decides when the moment has come, which may be after the loop has reached the tenth item or after a file has been read. JavaScript is built on that pattern, from array methods to event handlers and timers.

This lesson shows the callback in its three habitats. Inside a loop it is a function called once per item; in the error-first convention it is a function called once per operation, with the failure as its first argument; and in a chain of steps it is a function that starts the next one, which is where the nesting and the repeated error checks begin to hurt. The asynchronous part of the course comes back to all of it with promises.

A callback called in a loop

The function below walks an array and calls the callback once per item, with the value and the index. It ignores what the callback returns, because it is not building a result: the callback is called for its effect. That is the difference between forEach and map, and the program prints both to show it.

function each(items, callback) { for (let index = 0; index < items.length; index += 1) { callback(items[index], index); } } const names = ['ada', 'grace', 'alan']; each(names, (name, index) => { console.log(`${index + 1}. ${name}`); }); const upper = names.map((name) => name.toUpperCase()); console.log('map returns a new array:', upper.join(',')); const ignored = names.forEach((name) => name.toUpperCase()); console.log('forEach returns:', ignored);

node loop.js

1. ada
2. grace
3. alan
map returns a new array: ADA,GRACE,ALAN
forEach returns: undefined

The numbering came from the callback, which the loop called with a value and an index it never looked at. The last two lines are the warning: map collects what the callback returns, and forEach throws it away, so a forEach used where a map was meant is a program that computes something and drops it. The loop also shows the older convention of passing the index as the second argument, which the next lesson uses.

The error-first convention

A callback that reports the result of an operation has two things to report: the failure and the value. The convention that Node.js made standard puts the error first and the value second, and a successful call passes null in the first position. The callback checks the error before it touches the value, and returns early when there is one.

function readConfig(path, callback) { if (!path.endsWith('.json')) { callback(new Error(`not a json file: ${path}`), null); return; } callback(null, { path, retries: 3 }); } readConfig('app.json', (error, config) => { if (error) { console.log('failed:', error.message); return; } console.log('loaded:', config.path, 'retries:', config.retries); }); readConfig('app.yaml', (error, config) => { if (error) { console.log('failed:', error.message); return; } console.log('this line never runs:', config.path); });

node errorfirst.js

loaded: app.json retries: 3
failed: not a json file: app.yaml

Both callbacks have the same two parameters whatever happened, so the shape of the call never changes. The early return is not decoration: without it, a failed call would fall through to the line that reads config.path and throw a TypeError from inside the callback, where the original error is already lost. The convention is old and still everywhere in the standard library, which is why reading it is part of reading Node.js code.

Where callbacks stop scaling

Three steps that each need the result of the previous one become three nested callbacks, and each level repeats the error check and the early return. The program below does exactly that with a step function that cannot fail, so the shape is the only thing on show: the indentation grows by two spaces per step, and the value travels through every level.

function step(name, value, callback) { callback(null, `${value}>${name}`); } step('read', 'start', (readError, read) => { if (readError) { console.log(readError.message); return; } step('parse', read, (parseError, parsed) => { if (parseError) { console.log(parseError.message); return; } step('check', parsed, (checkError, checked) => { if (checkError) { console.log(checkError.message); return; } console.log('done:', checked); }); }); });

node nesting.js

done: start>read>parse>check

Six lines of error handling for three steps, and a fourth step would add two more. The problems compound: a variable declared inside one level is invisible to the next, a try around the outer call cannot catch a throw from an inner callback that runs later, and the sequence is written inside out, so the last step sits in the middle of the text. The nesting itself is not the whole complaint; the repeated error checks and the lost return are what a promise chain later removes. The next lesson turns to the array methods, which are callbacks seen from the other side: the caller hands over a function and the method decides when to call it, with the arguments and the order already settled.

A callback that calls itself

A callback can start another attempt, which is how a retry loop is written without a loop. The function below keeps a count of attempts left, calls the task, and on failure decides whether to try again or to give up. The task it receives fails twice and then succeeds, so the output shows the count of attempts in one line.

function withRetries(task, attempts, callback) { let left = attempts; function tryOnce() { left -= 1; task((error, value) => { if (!error) { callback(null, value); return; } if (left === 0) { callback(error, undefined); return; } tryOnce(); }); } tryOnce(); } let runs = 0; function flaky(callback) { runs += 1; if (runs < 3) { callback(new Error(`attempt ${runs} failed`), undefined); return; } callback(null, 'ok'); } withRetries(flaky, 5, (error, value) => { if (error) { console.log('gave up:', error.message); return; } console.log('succeeded with:', value, 'after', runs, 'attempts'); });

node retry.js

succeeded with: ok after 3 attempts

The retry is a small state machine with a counter and two exit branches, and it is honest about both outcomes: the callback receives the success value or the last error, never both and never neither. Written with plain callbacks, this is about as far as the style goes comfortably. A task that also needs a delay would nest a timer inside the retry, and the next step after that is the promise, which is the subject of the asynchronous part of the course.

Exercises

  1. Change each in loop.js to pass only the value. Which part of the arrow callback has to change, and what does the numbering print?
  2. Pass a plain function to readConfig that returns a value instead of printing one. Where does that value go?
  3. Add a fourth step to nesting.js. How many lines of error handling does the program now have, and how deep is the deepest callback?
  4. Call withRetries in retry.js with one attempt. What does the callback receive, and how many times does flaky run?
  5. Make the task in retry.js succeed on the first attempt. Which branch of the callback runs, and what does runs report?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a callback?

    Answer

    A function passed to another function, which calls it

    The caller supplies the code and the receiving function decides when and with which arguments to run it.

  2. What does forEach return?

    Answer

    undefined

    The method calls the callback for its effect and collects nothing, which is why map is the one that builds a result.

  3. What does this program print? function each(items, cb) { for (const item of items) cb(item); } const out = []; each([1, 2], (n) => out.push(n * 10)); console.log(out.join(","));

    Answer

    10,20

    The callback runs once per item and pushes the multiplied value into the array outside the loop.

  4. What does this program print? const result = [1, 2].forEach((n) => n * 2); console.log(result);

    Answer

    undefined

    forEach discards what the callback returns, so the value of the call is undefined and the multiplication is lost.

  5. Which argument comes first in the error-first convention?

    Answer

    The error, with null when the call succeeded

    The failure is the first thing a callback sees, so the check comes before any use of the value.

  6. What does this program print? function load(cb) { cb(new Error("missing"), null); } load((error, data) => console.log(data === null, error.message));

    Answer

    true missing

    The failing call passes null as the value, and the callback reads the message from the error object.

  7. Why does an error-first callback start with if (error) return?

    Answer

    So the success path never runs with a missing value

    Without the early return the callback continues after a failure and throws a confusing error of its own.

  8. What grows with every step in a nested callback chain?

    Answer

    The indentation and the number of error checks

    Each step adds a level and repeats the same guard, which is what makes the style hard to read at four levels.

  9. Why can a try around a call not catch an error thrown later inside a callback?

    Answer

    The callback runs after the try block has finished

    A try only covers the synchronous call, and the error of a later callback belongs to whoever calls it then.

  10. What does this program print? let calls = 0; function each(items, cb) { items.forEach(cb); } each([1, 2, 3], () => { calls += 1; }); console.log(calls);

    Answer

    3

    The callback runs once for each of the three items, so the counter ends at three.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev