Promises in jQuery: Simple Example

Problem Statement

  • You’ve a Master Form containing multiple child forms.
  • Child forms are submittable on their own, and have separate API end-points i.e. Child forms 1,2 & 3 will be processed by api1, api2 and api3 as services (say).
  • But Master form can only be submitted if
    • all of it’s inputs are valid
    • all inner forms are valid and have been submitted already
Multiple child forms with in a Master Form
Multiple child forms with in a Master Form

Solution Approach

Nested forms are not possible in HTML because a form can have only one action path.

So, ajax FTW.

Using Nested Ajax Calls

Nest successive ajax calls inside the success callbacks of the previous $.ajax  call and nest the final master form submission callback inside the last ajax request callback.

       ... //submit the master form after the last call is done

Click Here: To view Full Code


  • every request has to wait until the previous has finished i.e. 2nd ajax has to wait until the 1st request is resolved, and so on
  • If one of them fails, then all subsequent calls fail

Using Deferred Objects

Asynchronous requests are fired independently.$.ajax returns a promise object. Collect them in variables. The final callback will be triggered as soon as all of deferred objects are resolved in $.when(). 

Solution with deferred objects looks like:

var v1 = $.ajax1({ ... });
var v2 = $.ajax2({ ... });
var v3 = $.ajax3({ ... });
$.when( v1, v2, v3 ).done(function(){
  ...   //final submission of the form
...   //rest of your code
  • No Nesting
  • No Waiting per request
  • $.when will wait until all promises in arguments are resolved
  • .done( ) is fired when all promises are resolved – ideal place to pass the final callback

Click Here: To View Full Code

Code Snippet 1

  success: function( apiResponse1 ){
        success: function( apiResponse2 ){
              success: function( apiResponse3 ){
                  //Final ajax
            });//3rd ajax
      });//2nd ajax

Code Snippet 2

  api1 = $.ajax({
    url: "",
    success : function( response1 ){ isValid1 = response1.isValid; }

  api2 = $.ajax({
    url: "",
    success : function( response2 ){ isValid2 = response2.isValid; }

  api3 = $.ajax({
    url: "",
    success : function( response3 ){ isValid3 = response3.isValid; }

$.when( api1, api2, api3 ).done(function(){

      url: "",
      success : function(){
        ... //final call


One thought on “Promises in jQuery: Simple Example

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s