ThomasBurleson
2/25/2012 - 6:45 PM

Using $.post() with Promises

Using $.post() with Promises

// an IIFE that illustrates different implementations
// of $.post() with Promises
//
// Check out jsFiddle `jQuery and Promises with UI animation` 
//   - demonstrates $.Deferrred() and custom $.when()
//   - @ http://jsfiddle.net/ThomasBurleson/RTLr6/179/
//
var onSubmitFeedback = (function () {

  var target   = $("#container").append("<div class='spinner'>");

  var onDone        = function() { target.append("<p>Thank you for your feedback!</p>"); };
  var onError       = function() { target.append("<p>There was an error contacting the server.</p>"); };
  var onHideSpinner = function() { target.remove( ".spinner" ); }


  // Solution #1
  // Here we use the $.post() promise interface to do the work
  // This is obviously the easiest to maintain
  var onSubmitFeedback1 = function() {
    var comment = $("textarea", this).val();

    $.post( "/feedback", comment)
     .then( onDone, onError )   
     .always( onHideSpinner );

    return false;  // prevent default form behavior<br/>
  }


  // Solution #2
  // Here we use the promise :pipe() feature to sequence
  //multiple promises. This is the most `non-intuitive` approach
  var onSubmitFeedback2 = function() {

    $.Deferred( function(dfd) {
      var comment = $("textarea", this).val();
      
      dfd.resolve( comment )
         .pipe( function( comment ){
           return $.post( "/feedback", comment);
         });
    })
    .promise()
    .then( onDone, onError )
    .always ( onHideSpinner );

    return false;  // prevent default form behavior<br/>
  }

  // Solution #3
  // Here we use the $.Deferred() constructor parameter to do the work.
  var onSubmitFeedback3 = function() {
    
    $.Deferred( function(dfd) {
        var comment = $("textarea", this).val();
        
        $.post( "/feedback", comment)
         .success( function(){ dfd.resolve( comment ); })
         .error  ( function(){ dfd.reject();           })

    })
    .promise()
    .then( onDone, onError )
    .always ( onHideSpinner );

    return false;  // prevent default form behavior<br/>
  }

  // Solution #1 is the most obvious implementation
  reutrn onSubmitFeedback1;

})();


// DOM interaction
$("#feedback").submit( onSubmitFeedback );