Possible duplicate:
What are the differences between deferred, promises, and future ones in Javascript?
Recently, I have been making efforts to improve the quality of my JavaScript applications.
One template that I have adopted is to use a separate “data context” object to load data for my application (previously I did this directly in view models).
The following example returns data that is initialized by the client:
var mockData = (function($, undefined) { var fruit = [ "apple", "orange", "banana", "pear" ]; var getFruit = function() { return fruit; }; return { getFruit: getFruit } })(jQuery);
In most cases, we will download data from the server so that we cannot return an immediate response. It seems that I have two options for how we deal with this in our API:
I always used the callback approach before:
var getFruit = function(onFruitReady) { onFruitReady(fruit); }; // ... var FruitModel = function(dataContext, $) { return { render: function() { dataContext.getFruit(function(fruit) { // do something with fruit }); } }; };
However, I see how you can end up in the opposite hell, especially when creating complex JavaScript applications.
Then I came across a Promises design template. Instead of requiring the caller to call the callback, I instead return a “promise” that can be observed:
var getFruit = function() { return $.Deferred().resolve(fruit).promise(); };
I see the obvious advantages of using this template, especially since I can wait on several pending objects, which can be very useful when loading initialization data for a single-page application.
However, I really want to understand the pros and cons of each template before I start using it either in anger. I am also interested in whether this is a direction that other libraries are entering. This is similar to jQuery.
Here is a link to the script that I use for testing.