Conceptintro
Callback
Also called call-back, synchronous callback, asynchronous callback, deferred callback, callback argument.
A callback is a function that a program gives to another function, so that the other function can call it now or later. Sort comparators, event handlers and timer functions are callbacks.
- Applies to
- core-languages
Idea
A callback is a function that one part of a program gives to another part, and the other part calls it. MDN gives the definition: "A callback function 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
The function that receives the callback can call it at once, or it can keep it and call it later.
import atexit
def each(items, callback):
for item in items:
callback(item)
def goodbye():
print("goodbye")
atexit.register(goodbye)
each([1, 2, 3], lambda x: print("item", x))
print("end of main")
item 1
item 2
item 3
end of main
goodbye
each calls its callback three times before it returns. atexit.register keeps the function goodbye, and Python calls it when the program ends, after the last line of the main code.
How it works
- The consumer writes a function. "The consumer of a callback-based API writes a function that is passed into the API."1
- The consumer gives it to the provider. Wikipedia says that "a function reference is passed from one context (consumer) to another (provider) such that the provider can call the function."2 The function is an argument, or the consumer registers it, as with an event handler2.
- The provider calls it. "The provider of the API (called the caller) takes the function and calls back (or executes) the function at some point inside the caller's body."1 The provider gives the arguments: "The caller is responsible for passing the right parameters into the callback function."1
- The result. "The caller may also expect a particular return value from the callback function, which is used to instruct further behavior of the caller."1 In
qsort, the result of the comparison callback tells the sort the order of two items3.
Now or later
MDN gives two kinds: "Synchronous callbacks are called immediately after the invocation of the outer function, with no intervening asynchronous tasks, while asynchronous callbacks are called at some point later, after an asynchronous operation has completed."1 Wikipedia says the same in other words: "A function that accepts a callback parameter may be designed to call back before returning to its caller. But, more typically, a callback reference is stored by the provider so that it can call the function later (as deferred)."2
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin functions take parameters of function types, and a caller passes a lambda or a function reference. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Standard SQL has no function values, so a query cannot pass a function to another function. |
| Bash | Idiom | |
| PowerShell | Idiom | A PowerShell function can take a script block as a parameter and call it with the & operator. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language. Event handler attributes hold JavaScript code, and the browser calls it. |
| CSS | Does not apply | CSS has no functions that a style sheet can pass. |
| Regular expressions | Does not apply | A regular expression has no functions. |
- Python. Any function or callable object. The
keyargument ofsorted"specifies a function of one argument that is used to extract a comparison key from each element in iterable"4.atexit.registerkeeps a function for later: "Register func as an exit handler."5 - JavaScript. Any function. "Examples of synchronous callbacks include the callbacks passed to Array.prototype.map(), Array.prototype.forEach(), etc. Examples of asynchronous callbacks include the callbacks passed to setTimeout() and Promise.prototype.then()."1 The parameter of
setTimeoutis "A Function to be executed after the timer expires."6 - TypeScript. The same as JavaScript, and a function type expression gives the type of the callback. In the handbook example
function greeter(fn: (a: string) => void), the type(a: string) => voidmeans "a function with one parameter, named a, of type string, that doesn’t have a return value"7. - Java. An object of a functional interface, often made with a lambda.
List.sort"Sorts this list according to the order induced by the specified Comparator"8. - C#. Delegates. "The ability to refer to a method as a parameter makes delegates ideal for defining callback methods."9
- C. Function pointers. "In assembly, C, C++, Pascal, Modula-2 and other languages, a callback function is stored internally as a function pointer"2. In
qsort, the "Function pointed to by comp is used for object comparison."3 See Function pointers and delegates. - C++. A function pointer, a lambda or another function object. A function that keeps a callback often stores it in a
std::function, "a general-purpose polymorphic function wrapper"10. - Go. Function values. "Slice sorts the slice x given the provided less function."11
- Rust. Closures and functions. The method
unwrap_or_elseofOption<T>"takes one argument: a closure without any arguments that returns a value T"12. It calls the closure only when the value isNone12. - Bash. The name of a function in a variable or an argument. The
trapbuiltin keeps a command for later: "The action is a command that is read and executed when the shell receives any of the signals sigspec."13 "If a sigspec is 0 or EXIT, action is executed when the shell exits."13
def repeat(n, callback):
for i in range(1, n + 1):
callback(i)
def tick(i):
print("tick", i)
print(" ".join(str(x) for x in sorted([3, 1, 2], key=lambda x: -x)))
repeat(2, tick)
3 2 1
tick 1
tick 2
- Verdict: native.
sortedcalls thekeyfunction for each item, andrepeatcalls the functiontickthat the program gives it.
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
void repeat(int n, const std::function<void(int)>& callback) {
for (int i = 1; i <= n; ++i) {
callback(i);
}
}
void tick(int i) {
std::cout << "tick " << i << '\n';
}
int main() {
std::vector<int> xs = {3, 1, 2};
std::sort(xs.begin(), xs.end(), [](int a, int b) { return a > b; });
for (std::size_t i = 0; i < xs.size(); ++i) {
std::cout << (i ? " " : "") << xs[i];
}
std::cout << '\n';
repeat(2, tick);
}
3 2 1
tick 1
tick 2
- Verdict: native.
std::sorttakes the comparison as a template parameter, so a lambda works.repeattakes astd::function, which can hold the functiontick, a lambda or another function object.
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Main {
static void repeat(int n, IntConsumer callback) {
for (int i = 1; i <= n; i++) {
callback.accept(i);
}
}
static void tick(int i) {
System.out.println("tick " + i);
}
public static void main(String[] args) {
List<Integer> xs = new ArrayList<>(List.of(3, 1, 2));
xs.sort((a, b) -> Integer.compare(b, a));
System.out.println(xs.stream().map(String::valueOf).collect(Collectors.joining(" ")));
repeat(2, Main::tick);
}
}
3 2 1
tick 1
tick 2
- Verdict: native.
List.sorttakes aComparator, andrepeattakes anIntConsumer. A lambda and the method referenceMain::tickmake objects of these functional interfaces.
#include <stdio.h>
#include <stdlib.h>
static int descending(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (y > x) - (y < x);
}
static void repeat(int n, void (*callback)(int)) {
for (int i = 1; i <= n; i++) {
callback(i);
}
}
static void tick(int i) {
printf("tick %d\n", i);
}
int main(void) {
int xs[] = {3, 1, 2};
qsort(xs, 3, sizeof xs[0], descending);
printf("%d %d %d\n", xs[0], xs[1], xs[2]);
repeat(2, tick);
return 0;
}
3 2 1
tick 1
tick 2
- Verdict: native. A C callback is a function pointer.
qsortcallsdescendingto compare two items, andrepeatcallstickthrough the parametercallback.
using System;
using System.Collections.Generic;
class Program
{
static void Repeat(int n, Action<int> callback)
{
for (int i = 1; i <= n; i++)
{
callback(i);
}
}
static void Tick(int i)
{
Console.WriteLine($"tick {i}");
}
static void Main()
{
var xs = new List<int> { 3, 1, 2 };
xs.Sort((a, b) => b.CompareTo(a));
Console.WriteLine(string.Join(" ", xs));
Repeat(2, Tick);
}
}
3 2 1
tick 1
tick 2
- Verdict: native.
List<T>.Sorttakes aComparison<T>delegate, andRepeattakes anAction<int>delegate. The method groupTickconverts to the delegate.
function repeat(n, callback) {
for (let i = 1; i <= n; i++) {
callback(i);
}
}
function tick(i) {
console.log(`tick ${i}`);
}
console.log([3, 1, 2].sort((a, b) => b - a).join(" "));
repeat(2, tick);
3 2 1
tick 1
tick 2
- Verdict: native.
sortcalls the comparison function, which returns a negative number, zero or a positive number.repeatcallstickbefore it returns, so both callbacks are synchronous.
function repeat(n: number, callback: (i: number) => void): void {
for (let i = 1; i <= n; i++) {
callback(i);
}
}
function tick(i: number): void {
console.log(`tick ${i}`);
}
console.log([3, 1, 2].sort((a, b) => b - a).join(" "));
repeat(2, tick);
3 2 1
tick 1
tick 2
- Verdict: native. The type
(i: number) => voidtells the compiler which functionsrepeataccepts as its callback.
package main
import (
"fmt"
"sort"
)
func repeat(n int, callback func(int)) {
for i := 1; i <= n; i++ {
callback(i)
}
}
func tick(i int) {
fmt.Println("tick", i)
}
func main() {
xs := []int{3, 1, 2}
sort.Slice(xs, func(i, j int) bool { return xs[i] > xs[j] })
fmt.Println(xs[0], xs[1], xs[2])
repeat(2, tick)
}
3 2 1
tick 1
tick 2
- Verdict: native.
sort.Slicecalls the less function with two indexes. The function literal reads the slicexsfrom the outer function.
fn repeat(n: i32, mut callback: impl FnMut(i32)) {
for i in 1..=n {
callback(i);
}
}
fn tick(i: i32) {
println!("tick {}", i);
}
fn main() {
let mut xs = vec![3, 1, 2];
xs.sort_by(|a, b| b.cmp(a));
let out: Vec<String> = xs.iter().map(|x| x.to_string()).collect();
println!("{}", out.join(" "));
repeat(2, tick);
}
3 2 1
tick 1
tick 2
- Verdict: native.
sort_bytakes a closure that compares two items.repeattakes any type that implementsFnMut(i32), and a function such astickimplements it too.
repeat() {
local n=$1 callback=$2
for ((i = 1; i <= n; i++)); do
"$callback" "$i"
done
}
tick() {
echo "tick $1"
}
printf '%s\n' 3 1 2 | sort -rn | paste -s -d ' ' -
repeat 2 tick
3 2 1
tick 1
tick 2
- Verdict: idiom. A Bash function is not a value, so
repeattakes the name of a function and runs it as a command. Thesortcommand takes options and no comparison function.
Variations and related ideas
- Blocking and deferred callbacks. "A blocking callback runs in the execution context of the function that passes the callback. A deferred callback can run in a different context such as during interrupt or from a thread."2
- Event handlers. "Often, consuming code registers a callback for a particular type of event. When that event occurs, the callback is called."2 MDN says: "An event handler is a particular type of callback."14 See Event-driven programming.
- Context data. A C callback gets only its arguments. A library can take one more pointer for the data of the caller: C11
qsort_spasses itscontextparameter to the comparison function3. In languages with closures, the callback captures the data. See Closure. - Promises and async functions. "For these reasons, most modern asynchronous APIs don't use callbacks. Instead, the foundation of asynchronous programming in JavaScript is the Promise"14. See Futures and promises and Async/await.
- The design pattern. The page Callback tells when to design an API around callbacks.
Pitfalls
An async callback that nobody waits for
forEach calls its callback and does not use the result: the return value of the callback "is discarded"15. An async function returns a promise, so forEach does not wait for it. "forEach() expects a synchronous function — it does not wait for promises."15 This is the example from MDN:
This code runs but gives a wrong answer on purpose.
const ratings = [5, 4, 5];
let sum = 0;
const sumFunction = async (a, b) => a + b;
ratings.forEach(async (rating) => {
sum = await sumFunction(sum, rating);
});
console.log(sum);
0
The program prints sum before any callback adds a rating. MDN gives the next step: "To run a series of asynchronous operations sequentially or concurrently, see promise composition."15 A for...of loop with await in an async function runs the steps one after another.
Not knowing when the callback runs
Code after a call can see the effects of the callback or not, as a function of the time of the call. MDN says: "Understanding whether the callback is synchronously or asynchronously called is particularly important when analyzing side effects."1 In its example, the program sets a variable in a callback and then prints the variable, and the output is 1 or 2 as a function of the kind of callback1. Read the documentation of the provider, and do not depend on the order when it does not give one.
Callbacks in callbacks
Steps that each take a callback nest inside each other. "Because we have to call callbacks inside callbacks, we get a deeply nested doOperation() function, which is much harder to read and debug."14 MDN calls this "callback hell" or the "pyramid of doom"14. Errors are hard to handle too: you often must handle errors at each level, "instead of having error handling only once at the top level."14 Use promises or async and await when the language has them.
Cost
A call to a callback is a call through a function value. In C and similar languages the provider holds "a function pointer"2, so the call is an indirect call. See Function pointers and delegates. A deferred callback keeps its data alive until the call. Python atexit keeps the arguments too: "Any optional arguments that are to be passed to func must be passed as arguments to register()."5
References
- Callback function, MDN Web Docs glossary, the whole page
- Callback (computer programming), Wikipedia, the introduction; Use; Event handling; Asynchronous action; Implementation
- qsort, qsort_s, C reference, cppreference.com, the declaration; the description
- Built-in Functions, The Python Standard Library, sorted
- atexit, Exit handlers, The Python Standard Library, the introduction; atexit.register
- Window, setTimeout() method, MDN Web Docs, the introduction; Parameters
- More on Functions, The TypeScript Handbook, Function Type Expressions
- Interface List, Java SE 25 API, sort
- Delegates, C# Programming Guide, the introduction; Delegates overview
- std::function, C++ reference, cppreference.com, the introduction
- Package sort, Go standard library, func Slice
- Closures, The Rust Programming Language, Capturing the Environment with Closures
- Bourne Shell Builtins, Bash Reference Manual, trap
- Introducing asynchronous JavaScript, MDN Web Docs, Callbacks
- Array.prototype.forEach(), MDN Web Docs, Parameters; Description
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 | W2 basic |
|
Tag VVCCP6 Edit this page History Report an error Markdown