Back to series
· 9 min read

Callback function


I. What Is a Callback Function

A callback function is a function that is passed as an argument to another function, and the receiving function calls it at the appropriate moment.

Its core isn't about how the function is defined, but about the fact that the right to call the function is handed over to other code.

For example, in JavaScript:

function processData(data, callback) {
    const result = data.toUpperCase();
    callback(result);
}

function printResult(value) {
    console.log(value);
}

processData("hello", printResult);

Execution process:

  1. Define the printResult function.
  2. Call processData, passing printResult in as an argument.
  3. processData finishes processing the data.
  4. processData actively calls callback.
  5. printResult executes and outputs the result.

Here, printResult is the callback function, and processData is the caller of the callback function.

1. Basic Characteristics of Callback Functions

Characteristic Description
Function as argument A function can be passed to another function
Deferred call The receiver does not necessarily execute the callback immediately
Transfer of call rights The receiver decides when to call the callback
Replaceable behavior Different functions can be passed in to change the processing logic
Extensibility Behavior can be extended without modifying the body of the original function

2. Callback Functions vs. Ordinary Functions

Ordinary functions are usually called directly by the caller, whereas callback functions are called by other functions or the system at an agreed-upon moment.

function sayHello() {
    console.log("Hello");
}

// Ordinary function call
sayHello();

// Passed as a callback function
function execute(callback) {
    callback();
}

execute(sayHello);

Note: a callback function is not a special function type.

At the language level, it is still an ordinary function; it is called a callback function only because of the way it is passed and called.


II. How Callback Functions Work

Callback functions depend on the language's function objects, parameter passing, and function-calling mechanisms.

The basic principle can be divided into three stages:

  1. Function definition: create an executable function object.
  2. Function passing: pass the function object as an argument to another function.
  3. Function call: the receiver calls the function at the agreed-upon moment.

1. Basic Execution Flow

flowchart TD
    A["Define callback function"] --> B["Define the function that receives the callback"]
    B --> C["Call the receiving function"]
    C --> D["Pass the callback function reference"]
    D --> E["Receiver executes its own logic"]
    E --> F["Call the callback function"]
    F --> G["Callback function executes"]
    G --> H["Return or continue with subsequent logic"]

    style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

2. When Callback Functions Are Called

The timing of a callback function's invocation is decided by the receiver; it is not limited to the moment after function execution ends.

Common invocation timings:

Invocation Timing Typical Scenario
Immediate call Executed after data processing completes
When conditions are met Validation passes, state changes
During a loop Array traversal, collection processing
After an async task completes Network requests, file reading
When an event occurs Clicks, keyboard input, message arrival
Timed trigger Timers, periodic tasks

For example:

function validate(value, callback) {
    if (value.length > 0) {
        callback(true);
    } else {
        callback(false);
    }
}

validate("hello", (result) => {
    console.log("验证结果:", result);
});

The callback here is only invoked when validate reaches the corresponding branch.

3. Passing Parameters to Callback Functions

A callback function can receive data passed in by the caller.

function calculate(a, b, callback) {
    const result = a + b;
    callback(result);
}

calculate(10, 20, function(result) {
    console.log(result);
});

The callback function's parameters are determined by the caller, and both sides need to follow the agreed parameter structure.

In actual development, it is usually necessary to clarify:

  • Number of parameters.
  • Order of parameters.
  • Parameter types.
  • Whether null is allowed.
  • Whether the return value is meaningful.
  • Whether it may throw an exception.

These conventions form the calling contract of the callback function.


3. Common Types of Callback Functions

Callback functions can be classified by execution timing and execution mode.

1. Synchronous Callback

A synchronous callback is a callback function that executes on the current call stack, usually completing before the receiving function returns.

function process(callback) {
    console.log("开始处理");
    callback();
    console.log("处理结束");
}

process(() => {
    console.log("执行回调");
});

Output:

Start processing
Execute callback
Processing finished

Execution characteristics:

  • The caller directly invokes the callback.
  • During callback execution, the current call flow usually waits for it to return.
  • After the callback finishes executing, the receiving function continues execution.
  • Exceptions from the callback may propagate up the current call stack.

Common scenarios:

  • Array iteration.
  • Data transformation.
  • Sort comparison functions.
  • Conditional checks.
  • Synchronous data processing.

For example, JavaScript's map:

const numbers = [1, 2, 3];

const result = numbers.map((item) => {
    return item * 2;
});

console.log(result);

map takes a callback function and calls it synchronously while iterating over the array.

2. Asynchronous Callback

An asynchronous callback is a callback function that does not execute immediately in the current call flow, but instead executes after an asynchronous task completes or a specified event occurs.

For example:

console.log("开始");

setTimeout(() => {
    console.log("异步回调");
}, 1000);

console.log("结束");

Output:

Start
End
Asynchronous callback

Asynchronous callbacks usually involve the event loop, task queue, or runtime scheduling mechanism.

Execution process:

flowchart TD
    A["Execute current code"] --> B["Submit asynchronous task"]
    B --> C["Continue executing subsequent code"]
    C --> D["Asynchronous task completes"]
    D --> E["Callback enters task scheduling queue"]
    E --> F["Wait until call stack meets execution conditions"]
    F --> G["Event loop schedules callback"]
    G --> H["Execute callback function"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note:

An asynchronous callback does not mean a new thread is necessarily created.

Taking the JavaScript browser environment as an example, asynchronous operations such as timers and network requests are coordinated by the runtime and the relevant underlying mechanisms, and callbacks are ultimately scheduled for execution by the event loop. The callback itself usually still executes on the JavaScript main thread.

3. One-time callbacks and repeated callbacks

They can also be classified by the number of invocations:

Type Description Example
One-time callback Executes only once A single network request completes
Multiple callback Can be executed multiple times Data streams, progress notifications
Conditional callback Executes when a condition is met Validation succeeded, state changed
Periodic callback Repeats on a fixed cycle Scheduled tasks

For example:

function download(callback) {
    callback(25);
    callback(50);
    callback(75);
    callback(100);
}

download((progress) => {
    console.log(`下载进度:${progress}%`);
});

The callback function is called multiple times, so you cannot assume that a callback will only execute once.


IV. Typical application scenarios for callback functions

Callback functions are a fundamental mechanism in many programming languages and frameworks.

1. Array traversal and data processing

Through callback functions, the specific processing logic is handed over to collection operation methods.

JavaScript:

const users = [
    { name: "Alice", age: 20 },
    { name: "Bob", age: 25 },
    { name: "Charlie", age: 30 }
];

const names = users.map(user => user.name);

console.log(names);

map does not need to know which fields the business logic wants to extract; it is only responsible for traversing and invoking the callback function passed in.

This approach separates the collection traversal mechanism from the business processing logic.

2. Event handling

Event-driven programs respond to external events by registering callback functions.

document.addEventListener("click", (event) => {
    console.log("发生点击事件", event);
});

Here:

  • addEventListener is the event registration interface.
  • click is the event type.
  • The callback function is the event handling logic.
  • event is the data passed when the event occurs.

After an event occurs, the browser runtime is responsible for scheduling the corresponding event handler function.

Typical flow of an event callback:

flowchart TD
    A["Register event listener"] --> B["Wait for event to occur"]
    B --> C["User triggers event"]
    C --> D["Browser creates event object"]
    D --> E["Find registered listeners"]
    E --> F["Schedule event callback"]
    F --> G["Execute event handling logic"]
    G --> H["Update page or business state"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

3. Network requests

In traditional asynchronous programming, network request results can be handled through callbacks.

function requestData(url, callback) {
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error("请求失败");
            }

            return response.json();
        })
        .then(data => {
            callback(null, data);
        })
        .catch(error => {
            callback(error, null);
        });
}

requestData("/api/users", (error, data) => {
    if (error) {
        console.error(error);
        return;
    }

    console.log(data);
});

This uses the error-first callback convention:

callback(error, result);

The convention is:

  • The first parameter represents the error.
  • The second parameter represents the successful result.
  • On success, the error parameter is usually null.
  • On failure, the result parameter is usually null.

This form is fairly common in traditional Node.js asynchronous APIs.

Note: the fetch above is actually based on Promises. The example merely wraps the Promise result in a callback interface; it does not mean the underlying network API itself uses a callback style.

4. Scheduled Tasks

The logic to be executed by a scheduled task is specified through a callback function.

setInterval(() => {
    console.log("定时执行任务");
}, 2000);

The timer is responsible for scheduling, while the callback function handles the specific business logic.

Note that the timer's trigger time does not guarantee precise execution of the callback. A busy main thread, event loop scheduling, and runtime load can all cause delays.

5. Plugins and Framework Extensions

A framework can provide callback interfaces that let users customize execution logic.

function createButton(label, onClick) {
    return {
        label,
        click() {
            if (typeof onClick === "function") {
                onClick();
            }
        }
    };
}

const button = createButton("提交", () => {
    console.log("执行提交操作");
});

button.click();

The framework defines when execution occurs, while the user provides the business behavior.

This design is commonly seen in:

  • UI component libraries.
  • Plugin systems.
  • Lifecycle hooks.
  • Middleware mechanisms.
  • Framework extension points.

V. Callback Functions and Inversion of Control (IoC)

One of the most important design benefits of callback functions is achieving Inversion of Control (IoC).

1. What Is Inversion of Control?

In the traditional calling style, business code directly controls the function invocation process.

function saveData() {
    console.log("保存数据");
}

function handleRequest() {
    saveData();
}

handleRequest actively decides when to call saveData.

With callback functions, the specific behavior can be handed over to the outside:

function handleRequest(callback) {
    console.log("处理请求");
    callback();
}

handleRequest(() => {
    console.log("保存数据");
});

In this case:

  • handleRequest controls the timing of execution.
  • The external caller provides the specific behavior.
  • The specific behavior is triggered by the receiver at the appropriate time.

This is a typical manifestation of inversion of control.

2. The Shift in Control

flowchart TD
    subgraph OLD["Traditional Direct Calls"]
        A["Business Code"] --> B["Call Specific Function"]
        B --> C["Execute Specific Logic"]
    end

    subgraph NEW["Callback Mechanism"]
        D["External Caller"] --> E["Pass in Callback Function"]
        E --> F["Framework or Receiver"]
        F --> G["Decide When to Call"]
        G --> H["Execute Callback Logic"]
    end

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style OLD fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style NEW fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

3. The Relationship Between Callbacks and Dependency Injection

Callback functions and dependency injection (DI) are related, but the two are not equivalent.

Comparison Dimension Callback Function Dependency Injection
Core Purpose Hand behavior over to an external provider Hand dependencies over to an external provider
Injected Object Usually function behavior Dependencies such as objects, interfaces, and functions
Typical Scenarios Event handling, asynchronous notification Services, repositories, configuration management
Design Focus When to call, how to pass arguments How dependencies are created and managed

A callback function can serve as one form of implementing dependency injection, but dependency injection also includes constructor injection, property injection, method injection, and other approaches.


VI. Callback Functions in Different Programming Languages

Callback functions are not a mechanism unique to JavaScript. As long as a language supports passing functions or callable objects to other code, a similar design can be implemented.

1. JavaScript

JavaScript treats functions as first-class citizens, and functions, anonymous functions, and arrow functions can all be passed directly.

function execute(callback) {
    callback("JavaScript");
}

execute((name) => {
    console.log(name);
});

Common applications:

  • Event listening.
  • Array operations.
  • Timers.
  • Asynchronous requests.
  • Callbacks in Promise chaining.

2. Python

In Python, functions are first-class objects and can be passed directly as arguments.

def execute(callback):
    callback("Python")

def print_message(name):
    print(name)

execute(print_message)

Lambda expressions can also be used:

execute(lambda name: print(name))

Common applications:

  • map(), filter().
  • The key parameter of sorting functions.
  • GUI event handling.
  • Decorators and framework hooks.
  • Asynchronous task callbacks.

3. Java

Java can implement the callback mechanism through functional interfaces.

import java.util.function.Consumer;

public class CallbackDemo {

    static void execute(Consumer<String> callback) {
        callback.accept("Java");
    }

    public static void main(String[] args) {
        execute(message -> {
            System.out.println(message);
        });
    }
}

Common callback forms in Java include:

Type Purpose
Runnable No parameters, no return value
Consumer<T> Takes a parameter, no return value
Function<T, R> Takes parameters and returns a result
Predicate<T> Takes a parameter and returns a boolean
Custom interface Defines a specific callback contract

Callbacks in Java do not necessarily have to use functional interfaces; they can also be implemented with ordinary interfaces and anonymous inner classes.

4. C++

C++ can implement callbacks through function pointers, function objects, and lambda expressions.

Function pointer:

#include <iostream>

void printMessage() {
    std::cout << "C++ callback" << std::endl;
}

void execute(void (*callback)()) {
    callback();
}

int main() {
    execute(printMessage);
    return 0;
}

Lambda expression:

#include <iostream>
#include <functional>

void execute(const std::function<void()>& callback) {
    callback();
}

int main() {
    execute([]() {
        std::cout << "Lambda callback" << std::endl;
    });

    return 0;
}

Common callback implementations in C++:

  • Function pointers.
  • Function objects (functors).
  • Lambda expressions.
  • std::function.
  • Template parameters and callable objects.

Note that std::function is a type-erased wrapper for callable objects, not the callback mechanism itself.

5. Go

Go implements callbacks by using function types as parameters.

package main

import "fmt"

func execute(callback func(string)) {
    callback("Go")
}

func main() {
    execute(func(name string) {
        fmt.Println(name)
    })
}

Common callback uses in Go:

  • HTTP handlers.
  • Sort comparison functions.
  • Middleware.
  • Notification of concurrent task completion.
  • The functional options pattern.

6. Rust

Rust can implement callbacks using generic bounds and closures.