Quantcast
Channel: Tech Aways » milcom
Viewing all articles
Browse latest Browse all 13

Handling jQuery AJAX callbacks with Promises

$
0
0

I was exploring the Asynchronous Features of Grails 2.3 through a sample application and had asked my friends to take a look at it through the FB page. Bhagwat Kumar commented that many Javascript frameworks like Node.js, AngularJS, jQuery etc already have it in their patterns.

The Promise pattern helps a lot in eliminating callback hell and spaghetti code. I decided to see the jQuery Promise -Deferred API in action. Turns out, using Promises with AJAX is really easy because they are implemented using the very pattern.

We can assign the ajax call to a variable and then register callbacks to them using the Promise-done-fail pattern.


var ajaxCall = jQuery.post(appRoot + jQuery(this).attr("action"), jQuery(this).serialize());
ajaxCall.done(function(data){
     new Notification(data).init(); //Logic to add notification message on the page
}).fail(function(){
     new Notification("Something went wrong! Please try again later").init();
});

In this example, we make an AJAX call and assign it to the variable, ajaxCall. This is an instance of Promise. On this, we can then assign the success and failure callbacks of jQuery.ajax using the done and fail functions. For the complete callback, we can use the always() function of the Promise.

This pattern makes the code much more readable.


Viewing all articles
Browse latest Browse all 13

Trending Articles