Home

Callbacks

Callbacks are functions passed as arguments to other functions and invoked at a later time, typically to complete a task or respond to an event. They enable decoupling of the operation from the code that initiates it, making it possible to customize behavior without modifying the caller. Callbacks are a core mechanism in many programming languages and are implemented as function values or references to executable code.

In practice, callbacks are used in synchronous contexts (for example, when an array method applies a function

A frequent design in asynchronous environments is the error-first callback, common in Node.js, where the first

Potential pitfalls include accidental retention of objects via closures, inadvertent multiple invocations, and difficulties canceling pending

See also: function pointers, delegates, promises, futures, asynchronous programming, event-driven programming, continuation-passing style.

to
each
element)
and
asynchronous
contexts
(for
example,
when
an
I/O
operation
finishes
or
a
timer
fires).
Common
patterns
include
event
listeners,
where
a
callback
runs
in
response
to
an
event,
and
continuation-style
flows,
where
a
callback
processes
the
result
of
another
function.
In
languages
with
explicit
error
handling,
callbacks
may
take
multiple
parameters,
with
the
first
often
representing
an
error.
parameter
reports
an
error
and
subsequent
parameters
provide
results.
This
convention
helps
centralize
error
handling
but
can
lead
to
deeply
nested
code,
sometimes
called
callback
hell.
To
mitigate
complexity,
many
ecosystems
offer
alternatives
such
as
promises,
futures,
or
async/await,
which
represent
the
eventual
result
and
reduce
nesting.
callbacks.
Well-designed
APIs
document
the
callback’s
contract
and
lifecycle,
and
may
provide
cancellation
mechanisms.