javascript promises

Pyramid of Doom

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            // Do something with value3
        });
    });
});

...

    var calls = 0;
    var next = function() {
        calls += 1;
        if (calls === 2) {
            // Do something
        }
    }

    async('foo', next);
    async('bar', next);


[spaghetti intensifies]

all hail the Promise


"A promise is an object that represents the return value or the thrown exception that the function may eventually provide."

Promises/A+ Spec
http://promises-aplus.github.io/promises-spec/

Q
https://github.com/kriskowal/q

when
https://github.com/cujojs/when

AngularJS $q

$().promise()

.then()

    promiseMe()
    .then(function(result) {
        // Do something with result
    })
    .catch(function(error) {
        // Do something with error
    })
    .finally(function() {
        // Clean up
    });

serial calls


    promiseMe()
    .then(function(result) {
        // Do something with result
        return promiseSomethingElse();
    })
    .then(function(result2) {
        // Do something with result2
    });
        

parallel calls


    Q.all([
        promiseMe(),
        promiseSomethingElse()
    ]).then(function(results) {
        // Do something with both results
    }).catch(function(error) {
        // Handle error immediately
    });
        

isn't this where we came in?

var promiseMe = function(params) {
    return Q.nfcall(fs.readFile, params);
};
var promiseMe = function(params) {
    var deferred = Q.defer();
    
    // sometime later...
    deferred.resolve(value);
    
    return deferred.promise;
}

javascript promises

By Warren Seymour

javascript promises

  • 1,182