What sets deferred event objects apart from conventional callback implementations is their ability to support callback chaining. It is possible to attach multiple deferrable callback handlers to a single deferred event object such that when a callback is made the chained callback handlers are each invoked in turn. For the purposes of demonstrating this feature, the simple deferrable callback handler of Listing 5.5 is extended as shown in Listing 5.9.
Of particular interest in this version of the deferrable callback handler is that the onCallback method processes the input data and returns the modified version. In this case, it is simply a case of wrapping the string parameter with function-style parentheses. It is then possible to attach multiple deferrable callback handlers to the deferred event object as shown in Listing 5.10.
The example shown in Listing 5.10 also illustrates the use of the terminal parameter of the addDeferrable method. When adding the final deferrable in a chain the terminal flag must be set to true. This terminates the callback chain, making it ready for execution. For this reason, the final deferrable object in a callback chain is generally referred to as the terminal deferrable. Once a callback chain has been terminated, any attempt to add further deferrable callback objects will generate a runtime exception of type DeferredTerminatedException.
The full implementation of the chained callback example is present in the deferred examples package as DeferredChainExample1. Running the example code results in the console output shown in Listing 5.11. From this it is possible to see that processing the callback chain using the deferred event object is equivalent to making a set of nested function calls with the first callback method acting as the `innermost' function and the final callback method acting as the `outermost' function.