Futures and Promises in JavaScript

With JavaScript usage constantly on the increase, asynchronous event-driven applications are becoming more and more popular. However, a common issue many developers face is with result-dependent operations being used in an asynchronous environment, you often end up with something like:

doA(function(aResult) {
    // do some stuff inside b then fire callback
    doB(aResult, function(bResult) {
        // ok b is done, now do some stuff in c and fire callback
        doC(bResult, function(cResult) {
            // finished, do something here with the result from doC()
        });
    });
});

Since each step requires the previous steps result, you will regularly see a pattern where people start nesting the callback functions within each other’s callbacks. These nested callbacks become difficult to maintain, understand and follow in larger asynchronous applications. Simple async flow such as do (A + B + C) then do D becomes an increasingly complex task.

A solution to use in this situation is the Promise / Futures pattern, which represents the result of a callback that has not happened yet. The concept is quite simple, instead of a function blocking and waiting to complete before returning the result, it simply returns immediately when invoked with an object that promises the future computation / result. This results in a non-blocking behaviour:

doA()
    .then(function() { return doB(); })
    .then(function() { return doC(); })
    .done(function() { /* do finished stuff here */ });

Writing your code using the Promise / Future pattern gives you most of the benefits of using nested callbacks, along with a cleaner, more structured code that is easier to maintain, understand and follow in most asynchronous environments.

Promises / Futures are not the ultimate solution, and there are dozens upon dozens of other solutions that all have their own benefits and drawbacks, each which should be explored in their own right for different situations.

Comments

  1. Pingback: JavaPins

Leave a Reply

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


five − = 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>