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
- Is used by: Event-driven programming
- An alternative to: Future and promise
- See also: Asynchrony, Event loop
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¶
- In the books: Asynchronous Programming in Rust, Carl Fredrik Samson — ch. 2, 'How Programming Languages Model Asynchronous Program Flow' → 'Callback based approaches'
- In the books: asyncio Recipes, Mohamed Mustapha Tahrioui — ch. 2, 'Working with Event Loops' → 'Scheduling Callbacks on a Loop'
- In the books: JavaScript Concurrency, Adam Boduch — ch. 3, 'Synchronizing with Promises' → 'Building callback chains'
- In the books: Combine: Asynchronous Programming with Swift, Shai Mishali, Florent Pillet, Marin Todorov, Scott Gardner — ch. 8, 'In Practice: Project "Collage Neue"' → 'Wrapping a callback function as a future'
- In the books: Kotlin Coroutines by Tutorials, Filip Babić, Nishant Srivastava — ch. 1, 'What Is Asynchronous Programming' → 'Handling work completion using callbacks'
- In the books: Grokking Concurrency, Kirill Bobrov — ch. 11, 'Event-based concurrency' → 'Callbacks'
- Notes: Callback-Based - Asynchronous Programming ↗
- Reference: Wikipedia: Callback (computer programming) ↗