Programming Search⌘K

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")
Output
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

  1. The consumer writes a function. "The consumer of a callback-based API writes a function that is passed into the API."1
  2. 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.
  3. 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
  4. 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

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin 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.
SQLDoes not applyStandard SQL has no function values, so a query cannot pass a function to another function.
BashIdiom
PowerShellIdiomA 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.
HTMLDoes not applyHTML is a markup language. Event handler attributes hold JavaScript code, and the browser calls it.
CSSDoes not applyCSS has no functions that a style sheet can pass.
Regular expressionsDoes not applyA regular expression has no functions.
  • Python. Any function or callable object. The key argument of sorted "specifies a function of one argument that is used to extract a comparison key from each element in iterable"4. atexit.register keeps 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 setTimeout is "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) => void means "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_else of Option<T> "takes one argument: a closure without any arguments that returns a value T"12. It calls the closure only when the value is None12.
  • Bash. The name of a function in a variable or an argument. The trap builtin 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
PythonGitHub
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)
Output
3 2 1
tick 1
tick 2
  • Verdict: native. sorted calls the key function for each item, and repeat calls the function tick that 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);
}
Output
3 2 1
tick 1
tick 2
  • Verdict: native. std::sort takes the comparison as a template parameter, so a lambda works. repeat takes a std::function, which can hold the function tick, a lambda or another function object.
JavaGitHub
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);
    }
}
Output
3 2 1
tick 1
tick 2
  • Verdict: native. List.sort takes a Comparator, and repeat takes an IntConsumer. A lambda and the method reference Main::tick make 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;
}
Output
3 2 1
tick 1
tick 2
  • Verdict: native. A C callback is a function pointer. qsort calls descending to compare two items, and repeat calls tick through the parameter callback.
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);
    }
}
Output
3 2 1
tick 1
tick 2
  • Verdict: native. List<T>.Sort takes a Comparison<T> delegate, and Repeat takes an Action<int> delegate. The method group Tick converts to the delegate.
JavaScriptGitHub
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);
Output
3 2 1
tick 1
tick 2
  • Verdict: native. sort calls the comparison function, which returns a negative number, zero or a positive number. repeat calls tick before it returns, so both callbacks are synchronous.
TypeScriptGitHub
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);
Output
3 2 1
tick 1
tick 2
  • Verdict: native. The type (i: number) => void tells the compiler which functions repeat accepts 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)
}
Output
3 2 1
tick 1
tick 2
  • Verdict: native. sort.Slice calls the less function with two indexes. The function literal reads the slice xs from the outer function.
RustGitHub
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);
}
Output
3 2 1
tick 1
tick 2
  • Verdict: native. sort_by takes a closure that compares two items. repeat takes any type that implements FnMut(i32), and a function such as tick implements it too.
BashGitHub
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
Output
3 2 1
tick 1
tick 2
  • Verdict: idiom. A Bash function is not a value, so repeat takes the name of a function and runs it as a command. The sort command takes options and no comparison function.
  • 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_s passes its context parameter 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);
Output
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

  1. Callback function, MDN Web Docs glossary, the whole page
  2. Callback (computer programming), Wikipedia, the introduction; Use; Event handling; Asynchronous action; Implementation
  3. qsort, qsort_s, C reference, cppreference.com, the declaration; the description
  4. Built-in Functions, The Python Standard Library, sorted
  5. atexit, Exit handlers, The Python Standard Library, the introduction; atexit.register
  6. Window, setTimeout() method, MDN Web Docs, the introduction; Parameters
  7. More on Functions, The TypeScript Handbook, Function Type Expressions
  8. Interface List, Java SE 25 API, sort
  9. Delegates, C# Programming Guide, the introduction; Delegates overview
  10. std::function, C++ reference, cppreference.com, the introduction
  11. Package sort, Go standard library, func Slice
  12. Closures, The Rust Programming Language, Capturing the Environment with Closures
  13. Bourne Shell Builtins, Bash Reference Manual, trap
  14. Introducing asynchronous JavaScript, MDN Web Docs, Callbacks
  15. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • the section History