A callback function is a function that is passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action. In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. Callbacks are used to program applications in windowing systems, where the application supplies a specific custom callback function for the operating system to call, which then calls this application-specific function in response to events like mouse clicks or key presses). Callbacks have a wide variety of uses, for example in error signaling, where a Unix program might not want to terminate immediately when it receives SIGTERM, so to make sure that its termination is handled properly, it would register the cleanup function as a callback).
A callback function can be called synchronously or asynchronously. 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. Understanding whether the callback is synchronously or asynchronously called is particularly important when analyzing side effects.
Callbacks are used because they allow us to reuse our code, and they can become extremely powerful when used properly. When it comes to asynchronous programming, callbacks are essential because they allow us to tell a function what to do once it’s done with a task.