What Is a Callback? A Function Passed to Be Called Later
A callback is a function you pass to other code so that code can call it back later, commonly when an event happens or an asynchronous task completes.
Callbacks are one of the oldest ways to handle "do this when that finishes." You hand a function to an API; the API holds onto it and invokes it at the right moment, such as when data arrives or a timer fires. Callbacks are simple and everywhere, but nesting many of them leads to the tangled style often called "callback hell."
What makes a callback
A callback is just a function used as a value: passed as an argument to be invoked later. The receiving code decides when and with what arguments to call it. This inverts control: you provide behavior, the framework decides timing.
Where callbacks show up
- Event handlers, like a click or a message received.
- Asynchronous I/O completion, such as a file read finishing.
- Higher-order functions like map, filter, and reduce.
- Timers and scheduling, like setTimeout and setInterval.
Callback hell
When one async step depends on the result of another, callbacks nest inside callbacks, deepening with each step. The code drifts rightward and becomes hard to read and to handle errors in. Promises and async/await were created largely to flatten this.
Error handling with callbacks
A common convention passes an error as the first callback argument (the "error-first" pattern). It works but is easy to get wrong: forget to check the error and a failure passes silently, which is one reason promises took over.
A quick example
In arr.forEach(item => console.log(item)), the arrow function is a callback: forEach calls it once per element, and you never call it directly yourself.
Callbacks in CI
Tests that rely on a callback firing can hang or flake if the callback never runs or runs after the assertion. Such timing bugs fail intermittently on busy runners. Latchkey auto-retries transient failures while you stabilize callback-driven tests, so one flaky run does not block a merge.
Key takeaways
- A callback is a function passed to other code to be invoked later.
- It is the basis of event handling and old-style async, but nesting causes callback hell.
- Promises and async/await largely replaced deep callback chains.