Patternintro
Callback
Also called callback, callback function, call-after function.
A callback is a function that one part of a program passes to another part, so that the other part can call it, now or later.
- Family
- behavioral-design
- Intent
- Pass a function reference from a consumer to a provider, so that the provider can call the function back.
- Also called
- callback function
Intent
A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.1
Problem
A general function often needs one step that only its caller knows. A sort routine needs to know the order of two items. A window system needs to tell the program about a mouse click. A slow operation needs to say when it is done.2
The general function cannot contain this step, because the step is different for each caller.
Solution
The consumer passes a function reference to the provider, and the provider calls the function. If the function uses state or functionality of the consumer, then the call goes back to the consumer, opposite to the normal flow of control.2
consumer provider
| call provider(callback) |
|-------------------------------->|
| | ... does its work ...
| callback(arguments) |
|<--------------------------------| calls back, now or later
The provider can call the callback before it returns to its caller. More typically, the provider stores the callback reference and calls the function later, as a deferred callback.2 Wikipedia compares a callback to instructions that you give to a tailor for what to do when a suit is ready, such as a phone number to call.2
MDN names two ways to call a callback.1
- Synchronous. The callback is called immediately after the invocation of the outer function, with no intervening asynchronous tasks. The callbacks passed to
Array.prototype.map()andArray.prototype.forEach()are examples. - Asynchronous. The callback is called at some point later, after an asynchronous operation has completed. The callbacks passed to
setTimeout()andPromise.prototype.then()are examples.
Example
The example files show one program in each language. First, for_each calls the callback shout once for each word, before it returns. Then a queue stores a second callback, and the program continues. The queue calls the stored callback only when it runs. The program prints:
HELLO
WORLD
request sent
saved
def for_each(items, callback):
for item in items:
callback(item) # a blocking callback: called before for_each returns
class Queue:
def __init__(self):
self.pending = []
def later(self, callback):
self.pending.append(callback) # stored, to be called later
def run(self):
while self.pending:
self.pending.pop(0)()
def shout(word):
print(word.upper())
for_each(["hello", "world"], shout)
queue = Queue()
queue.later(lambda: print("saved")) # a deferred callback
print("request sent")
queue.run()
HELLO
WORLD
request sent
saved
- Verdict: native. Functions are values, and a lambda can be passed directly.
#include <cctype>
#include <deque>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
void forEach(const std::vector<std::string>& items, const std::function<void(const std::string&)>& callback) {
for (const auto& item : items) callback(item); // a blocking callback
}
int main() {
forEach({"hello", "world"}, [](const std::string& w) {
std::string up = w;
for (char& c : up) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
std::cout << up << "\n";
});
std::deque<std::function<void()>> pending;
pending.push_back([] { std::cout << "saved\n"; }); // a deferred callback
std::cout << "request sent\n";
while (!pending.empty()) {
pending.front()();
pending.pop_front();
}
}
HELLO
WORLD
request sent
saved
- Verdict: stdlib.
std::functionholds any callable object, such as a lambda.
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
import java.util.function.Consumer;
public class Main {
static <T> void forEach(List<T> items, Consumer<T> callback) {
for (T item : items) callback.accept(item); // a blocking callback
}
public static void main(String[] args) {
forEach(List.of("hello", "world"), word -> System.out.println(word.toUpperCase()));
Queue<Runnable> pending = new ArrayDeque<>();
pending.add(() -> System.out.println("saved")); // a deferred callback
System.out.println("request sent");
while (!pending.isEmpty()) pending.poll().run();
}
}
HELLO
WORLD
request sent
saved
- Verdict: stdlib. Functional interfaces such as
ConsumerandRunnableare the callback types, and lambdas implement them.
using System;
using System.Collections.Generic;
static void ForEach<T>(IEnumerable<T> items, Action<T> callback)
{
foreach (var item in items) callback(item); // a blocking callback
}
ForEach(new[] { "hello", "world" }, word => Console.WriteLine(word.ToUpper()));
var pending = new Queue<Action>();
pending.Enqueue(() => Console.WriteLine("saved")); // a deferred callback
Console.WriteLine("request sent");
while (pending.Count > 0) pending.Dequeue()();
HELLO
WORLD
request sent
saved
- Verdict: native. Delegates such as
Action<T>are the callback types.
function forEach(items, callback) {
for (const item of items) callback(item); // a blocking callback
}
const shout = (word) => console.log(word.toUpperCase());
forEach(["hello", "world"], shout);
setTimeout(() => console.log("saved"), 0); // an asynchronous callback
console.log("request sent");
HELLO
WORLD
request sent
saved
- Verdict: native. Functions are values.
setTimeout()takes an asynchronous callback, so "saved" comes after "request sent".
function forEach<T>(items: T[], callback: (item: T) => void): void {
for (const item of items) callback(item); // a blocking callback
}
const shout = (word: string): void => console.log(word.toUpperCase());
forEach(["hello", "world"], shout);
setTimeout(() => console.log("saved"), 0); // an asynchronous callback
console.log("request sent");
HELLO
WORLD
request sent
saved
- Verdict: native. A function type such as
(item: T) => voidgives the type of the callback.
package main
import (
"fmt"
"strings"
)
func forEach(items []string, callback func(string)) {
for _, item := range items {
callback(item) // a blocking callback
}
}
func main() {
forEach([]string{"hello", "world"}, func(w string) { fmt.Println(strings.ToUpper(w)) })
var pending []func()
pending = append(pending, func() { fmt.Println("saved") }) // a deferred callback
fmt.Println("request sent")
for _, f := range pending {
f()
}
}
HELLO
WORLD
request sent
saved
- Verdict: native. Functions are values, and
sort.Slicetakes a less function in the same way.
use std::collections::VecDeque;
fn for_each(items: &[&str], callback: impl Fn(&str)) {
for item in items {
callback(item); // a blocking callback
}
}
fn main() {
for_each(&["hello", "world"], |w| println!("{}", w.to_uppercase()));
let mut pending: VecDeque<Box<dyn FnOnce()>> = VecDeque::new();
pending.push_back(Box::new(|| println!("saved"))); // a deferred callback
println!("request sent");
while let Some(f) = pending.pop_front() {
f();
}
}
HELLO
WORLD
request sent
saved
- Verdict: native. A blocking callback can be a generic
impl Fn. A stored callback is often aBox<dyn FnOnce()>.
Consequences
The benefits:
- One general function can serve many callers. In C,
qsort()andbsearch()take a comparator function that determines the collation order.2 - A program can react to events. The consuming code registers a callback for a type of event, and the callback is called when that event occurs.2
- A caller can request a slow action and continue. The callback is called when the action completes, which might be long after the request.2
The costs:
- The caller must know whether the callback is called synchronously or asynchronously. This is particularly important for side effects.1
- Steps in a sequence give nested callbacks. Several asynchronous operations in a row lead to the classic "callback hell", and the error callback is repeated at each level.3
- The provider must call the callback the correct number of times. In Node.js, a callback is almost always meant to be called only once, and a second call is the error
ERR_MULTIPLE_CALLBACK.4
Here the program reads a value before a deferred callback has run. The callback changes value to 2, but the first print shows the old value:
This code runs but gives a wrong answer on purpose.
import asyncio
async def main():
value = 1
def set_value():
nonlocal value
value = 2
asyncio.get_running_loop().call_soon(set_value) # deferred
print("value:", value) # the callback has not run yet
await asyncio.sleep(0)
print("later:", value)
asyncio.run(main())
value: 1
later: 2
When not to use it
- The operation is a sequence of asynchronous steps. Promises let each step attach its callback to a chain, so the error handler appears only once, at the end of the chain.3 With
asyncandawait, the code resembles synchronous code.3 - The provider must call several related functions. Then an object with an interface can be clearer than several separate callbacks.
Variants and related patterns
- Error-first callbacks. Most asynchronous methods of Node.js that accept a
callbackfunction pass anErrorobject as the first argument to that function. If that argument is notnulland is an instance ofError, an error occurred that should be handled.4 The convention looks like this in Python:
def read_config(name, callback):
if name != "app.toml":
callback(FileNotFoundError(name), None) # error first
return
callback(None, "debug = true")
def done(err, data):
if err is not None:
print("error:", err)
else:
print("data:", data)
read_config("app.toml", done)
read_config("missing.toml", done)
data: debug = true
error: missing.toml
- Function pointers, functors and lambdas. In C, C++ and Pascal, a callback can be a function pointer. In C++, a functor, an object with
operator(), can also be a callback. Many languages have lambda expressions, which often act as callbacks.2 - Observer and Command. An observer registers a callback for an event. A command object is a callback with its arguments, in the form of an object.
Known uses
- C sorting and searching. The C standard library functions
qsort(),lsearch()andbsearch()take a comparator function as an argument.2 - Go
sort.Slice. The functionSlice(x any, less func(i, j int) bool)sorts the slicexgiven the provided less function.5 - Node.js file system. In the Node.js documentation,
fs.readFiletakes a callback(err, data) =>that gets the error first.4 - JavaScript arrays and timers.
Array.prototype.map()andArray.prototype.forEach()take synchronous callbacks, andsetTimeout()takes an asynchronous callback.1
References
- Callback function, MDN Web Docs glossary, whole page
- Callback (computer programming), Wikipedia, lead; Use; Event handling; Asynchronous action; Implementation; Example code, C
- Using promises, MDN Web Docs, Chaining; Error handling
- Node.js v24.0.0 documentation source, doc/api/errors.md, Error propagation and interception, lines 83 to 86; ERR_MULTIPLE_CALLBACK, lines 2273 to 2279
- Go go1.25.0 source, src/sort/slice.go, func Slice and its comment, lines 12 to 24
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 2QAJS8 Edit this page History Report an error Markdown