dojo.Deferred would have been part two in my single part series on Method Chaining. It’s a pretty awesome way for setting up callback hierarchies for asynchronous programming:
function async() {
var d = new dojo.Deferred();
// Start something asynchronous,
// call d.callback(response) when done.
return d;
}
async().addCallback(function(response) {
alert('Ready!');
return response;
});
I can add multiple callbacks to async() or even chain them to the result of adding a callback:
async().addCallback(function(response) {
alert('Ready!');
return response;
}).addCallback(function(response) {
alert('Double ready!');
return response;
});
Parallel to the callback hierarchy, there’s an ‘errback’ hierarchy which is invoked in case a callback throws an error. This makes it easy to handle errors within the callback chain. Unfortunately it also prevents the error from being logged in the browser’s error console.
Luckily, it isn’t hard to log these errors ourselves. Simply run the following before using any deferreds:
;(function() {
var addCallback = dojo.Deferred.prototype.addCallback;
dojo.Deferred.prototype.addCallback = function() {
var cb = addCallback.apply(this, arguments);
cb.addErrback(console.error);
return cb;
};
})();
This overwrites the original addCallback method to automatically register an ‘errback’, which logs to console.error. Then, it returns the original return value, so it doesn’t affect other code.
Happy Dojo’ing!
