Skip to content

Callback

Category: Async · Status: stub · Lessons: chapter 06, Async (planned)

One line: A function handed to an operation to be called when the operation finishes — the oldest way to write asynchronous code, and the source of deeply nested callback code.

Also called: completion handler, callback hell.

How it connects

flowchart LR
  n_callback["Callback"]
  n_event_driven_programming["Event-driven programming"]
  n_future_and_promise["Future and promise"]
  n_callback ---|or| n_future_and_promise
  n_event_driven_programming -->|uses| n_callback
  classDef center stroke-width:3px
  class n_callback center
  classDef outside stroke-dasharray: 4 3
  class n_event_driven_programming,n_future_and_promise outside

In each language

C a function pointer; POSIX AIO ↗ can report a finished operation by starting a thread (SIGEV_THREAD)
Java CompletableFuture takes callbacks such as thenApply and thenAccept
Python Future.add_done_callback and loop.call_soon; asyncio futures exist to bridge callback-based code with async/await
C# the Asynchronous Programming Model ↗: BeginOperationName takes an AsyncCallback that is called when the operation completes
JavaScript a callback function ↗, passed into another function and invoked inside it
Swift completion handlers, which the Swift book ↗ shows piling up as nested closures before it introduces async and await

Where to read more