title: How to use jQuery's deferred object with custom javascript objects?
body: <p>I have a standard javascript object whose prototype is extended with a <code>.start()</code> method taking 2 callbacks as arguments: <code>success</code> and <code>failure</code> respectively. This method performs some asynchronous processing (it's <strong>not</strong> AJAX) and depending on the result of this processing it invokes either the success or the failure callbacks.</p>
  
  <p>Here's how this could be schematized:</p>
  
  <pre><code>function MyObject() {
  }
  
  MyObject.prototype.start = function(successCallback, errorCallback) {
      (function(s, e) {
          window.setTimeout(function() {
              if (Math.random() &lt; 0.8) {
                  s();    
              } else {
                  e();    
              }
          }, 2000);    
      })(successCallback, errorCallback);
  }
  </code></pre>
  
  <p>It's not really important the exact processing performed inside the method, only that it is asynchronous and non-blocking. I have no control over the point of time when the start method will finish the processing. I also have no control over the prototype and implementation of this method.</p>
  
  <p>What I have control over is the <code>success</code> and <code>failure</code> callbacks. It is up to me to provide them. </p>
  
  <p>Now I have an array of those objects:</p>
  
  <pre><code>var arr = [ new MyObject(), new MyObject(), new MyObject() ];
  </code></pre>
  
  <p>The order of elements in this array is important. I need to trigger the <code>.start()</code> method on each element of the array consecutively but only once the previous has completed (i.e. the success callback was called). And if an error occurs (the failure callback is called) I want to stop the execution and no longer invoke the .start method on the remaining elements of the array.</p>
  
  <p>I could implement this naively by using a recursive function:</p>
  
  <pre><code>function doProcessing(array, index) {
      array[index++].start(function() {
          console.log('finished processing the ' + index + ' element');
          if (index &lt; array.length) {
              doProcessing(array, index);
          }
      }, function() {
          console.log('some error ocurred');
      });
  }
  
  doProcessing(arr, 0);
  </code></pre>
  
  <p>This works fine but looking at the <a href="http://api.jquery.com/category/deferred-object/">jQuery's deferred Object</a> that was introduced in jQuery 1.5 I think that there is a room for improvement of this code. Unfortunately I don't feel very comfortable yet with it and I am trying to learn it.</p>
  
  <p>So my question is is it possible to adapt my naive code and take advantage of this new API and if yes, could you provide me with some pointers?</p>
  
  <p>Here's a <a href="http://jsfiddle.net/8CRzf/4/">jsfiddle</a> with my implementation.</p>