public
Last active

Using $.post() with Promises

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
// 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 );

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.