Friday, August 9, 2013

Using the Promises Pattern in Titanium

Promises are part of the commonjs standard and can be defined as "objects which represent the pending result of an asynchronous operation. [which can be used] to schedule further activity after the asynchronous operation has completed" [Fowler, April 2013]

I wanted to see how I could use a promise as part of a remote request in Titanium.  I could of course, simply pass an onLoad and/or onError callback when I invoked createHTTPClient, but using a promise in this manner gives one the ability to chain a number of asynchronous events and avoid the "Pyramid of Doom"

I decided to use Q from Kris Kowal for my Promises.  The first thing I did was write a commonjs module that wrapped Q and HTTPClient.  My code for this is here;


Now I can call my new qxhr module and chain my method calls like so


qxhr.create(conn)
.then(function(data) {
    //do something with the data
}, function(error) {
    //handle the error
});

or I could do

Q.fcall(qxhr.create(conn))
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (data) {
    // Do something
})
.catch(function (error) {
    // Handle any error from all above steps
})
.done();