The standard mechanism for chaining deferred callbacks described in Section 5.4 is sufficient for most applications. However, there are certain situations where it is useful to combine the callback chains encapsulated by two existing deferred event objects - effectively `splicing' the callback chains together to form one long callback sequence. This is facilitated by using the chain method on the Deferred interface. An example of this in use is shown in Listing 5.14. The full implementation of this example is present in the deferred examples package as DeferredChainExample3.
In the example, the full callback chain is split between two deferred event objects. The deferredFront object encapsulates those callbacks which will be executed first (the `front' of the callback chain) and the deferredBack object encapsulates those callbacks which will be executed last (the `back' of the callback chain). The example is written in such a way as to highlight a key feature of chaining multiple deferred event objects in this way, as illustrated by the console output shown in Listing 5.15.
The output of the example code demonstrates that the callback timing is slightly different from the case where a callback chain is constituted using a single deferrable event object. In that case, the callbacks will only be executed once the callback chain has been triggered by a callback or errback call and it has also been terminated by adding a terminal deferrable object. In the results shown in Listing 5.15, it may be seen that the callbacks associated with the `front' part of the callback chain execute before the `back' part of the callback chain has been terminated.
The reason that the callbacks in the `front' part of the callback chain execute early is an artifact of the way in which multiple deferred event objects are chained together. Rather than attempting to merge the callback chains of the two deferred event objects, the callback chain of the `front' deferred event object is implicitly terminated with a terminal deferrable object whose only responsibility is to issue a callback or errback call to the `back' deferred event object. This slight difference in callback timing is usually irrelevant, so for most purposes it is reasonable to treat the chain method as if it simply splices the callback chains of the two deferrable event objects together.