title: Asynchronous JavaScript - Callbacks vs Deferred/Promise
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/6801283/what-are-the-differences-between-deferred-promise-and-future-in-javascript">What are the differences between Deferred, Promise and Future in Javascript?</a>  </p>
  </blockquote>
  
  
  
  <p>Lately I've been making an effort to improve the quality of my JavaScript applications.</p>
  
  <p>One pattern I've adopted is to use a separate "data context" object to load data for my application (previously I was doing this directly in my view models).</p>
  
  <p>The following example returns data that is initialized on the client:</p>
  
  <pre><code>var mockData = (function($, undefined) {
  
      var fruit = [
          "apple",
          "orange",
          "banana",
          "pear"
          ];
  
      var getFruit = function() {
          return fruit;
      };
  
      return {
          getFruit: getFruit
      }
  })(jQuery);
  </code></pre>
  
  <p>In most cases we'll be loading data from the server so we can't return an immediate response. It seems I have two options for how we handle this in our API:</p>
  
  <ol>
  <li>Using a callback</li>
  <li>Returning a <a href="http://api.jquery.com/promise/" rel="nofollow noreferrer">promise</a>.</li>
  </ol>
  
  <p>Previously I'd always used the callback approach:</p>
  
  <pre><code>var getFruit = function(onFruitReady) {
      onFruitReady(fruit);
  };
  
  // ...
  
  var FruitModel = function(dataContext, $) {
      return {
          render: function() {
              dataContext.getFruit(function(fruit) {
                  // do something with fruit
              });
          }
      };
  };
  </code></pre>
  
  <p>However, I can see how it's possible to end up in callback hell, especially when building complex JavaScript applications.</p>
  
  <p>Then I came across the Promises design pattern. Instead of requiring the caller to supply a callback, I instead return a "promise" that can be observed:</p>
  
  <pre><code>var getFruit = function() {
      return $.Deferred().resolve(fruit).promise();
  };
  
  // ...
  dataContext.getFruit().then(function(fruit) {
      // do something with fruit
  });
  </code></pre>
  
  <p>I can see obvious benefits of using this pattern, especially since I can <code>wait</code> on multiple deferred objects which could be very useful when loading initialization data for a single page application.</p>
  
  <p>However, I'm keen to understand the pros and cons of each pattern before I start to use either in anger. I'm also interested in whether this is the direction other libraries are going in. It seems to be the case with jQuery.</p>
  
  <p>Here's a <a href="http://jsfiddle.net/benfosterdev/yenGc/3/" rel="nofollow noreferrer">link</a> to the fiddle I'm using for testing.</p>