The Callback Pattern: Continuation-Passing Style (CPS)

Learn about the continuation-passing style (CPS) and its different types in the Callback pattern.

Callbacks are the materialization of the handlers of the Reactor pattern. They’re one of those imprints that give Node.js its distinctive programming style.

Callbacks are functions that are invoked to propagate the result of an operation, and this is exactly what we need when dealing with asynchronous operations. In the asynchronous world, they replace the use of the return instruction, which, in turn, always executes synchronously. JavaScript is the ideal language for callbacks because functions are first-class objects and can be easily assigned to variables, passed as arguments, returned from another function invocation, or stored in data structures. Another ideal construct for implementing callbacks is closures. With closures, we can reference the environment in which a function was created; this way, we can always maintain the context in which the asynchronous operation was requested, no matter when or where its callback is invoked.

In this lesson, we’ll analyze this particular style of programming, which uses callbacks instead of return instructions.

The continuation-passing style (CPS)

In JavaScript, a callback is a function that’s passed as an argument to another function and is invoked with the result when the operation completes. In functional programming, this way of propagating the result is called the continuation-passing style (CPS).

It’s a general concept, and it’s not always associated with asynchronous operations. In fact, it simply indicates that a result is propagated by passing it to another function (the callback), instead of directly returning it to the caller.

Synchronous CPS

To clarify this concept, let’s take a look at a simple synchronous function:

Get hands-on with 1200+ tech skills courses.