More Promises in Javascript

The framework is evolving. I now have the following operations on a Promise:

  • then( function(result, ongoingPromise) )
  • then( function(result, ongoingPromise), function(failureReason, furtherInfo) )
  • otherwise( function(failureReason, furtherInfo, ongoingPromise) )
  • thenAlways( function(success, resultOrFail, ongoingPromise) )

The resultOrFail argument is either a result for success, or an array of [reason, furtherInfo] for failure. All methods take an optional scope argument to fit with Ext-JS’s approach to reduce the use of closures.

These three functions all return a new Promise which is based on the result of the contained handler method. This allows a whole chain of actions to be taken as a result of a failure path or a combined path. The handler for thenAlways can always propagate a failure by calling

ongoingPromise.reject.apply(ongoingPromise, result);

Maybe a convenience method will help developers.

Within a handler function the ongoingPromise has

  • defer()
  • deferUntil( Promise[] )
As well as the standard resolve(result) and reject(reason, furtherInfo), or just return a result or throw a reason.

There is a lot that could be added, for example a convenient method to make a new Promise based on all of a Promise’s dependants to save you keeping your own list and typing “Promise.when([….])”. I can add it if I need it.

The internals are now becoming more complex, with clearly three different types of Promise. There’s a NormalPromise, an OtherwisePromise and an AlwaysPromise. There is clear separation between the reject/resolve calls and their equivalents for passing information from upstream Promises. So far the separation can be handled using a Strategy Pattern for the two upstream handling methods. Strategy Pattern is very easy in Javascript when you can just assign function pointers on an instance at runtime.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.