Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active March 18, 2020 17:32
Show Gist options
  • Select an option

  • Save LeanSeverino1022/ecdee82dacb7ce7f7915888f63459127 to your computer and use it in GitHub Desktop.

Select an option

Save LeanSeverino1022/ecdee82dacb7ce7f7915888f63459127 to your computer and use it in GitHub Desktop.
[Multiple ajax calls in an array and handle callback when all are completed] create an array of promises so that once all promises are resolved you can run your callback #jQuery #cheatsheet #dump

Wait until all jQuery Ajax requests are done and then do something...

Example on when to use: I want that after all promises are resolved, do something. For example every ajax request adds the ajax response data in an array. I want to make sure all data has been added before doing something else.

#1

	// You can create an array of promises so that once all promises are resolved you can run your all done code.
    
  var promises = []
  ;for (var i = 0; i < $total_files; i++){
     /* $.ajax returns a promise*/      
     var request = $.ajax({
          /* your ajax config*/
     })

     promises.push( request);}

  $.when.apply(null, promises).done(function(){
     alert('All done')})

#2

  var d1 = $.Deferred();
  var d2 = $.Deferred();
  var d3 = $.Deferred();

  $.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
      console.log( v1 ); // v1 is undefined
      console.log( v2 ); // v2 is "abc"
      console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
  });

  d1.resolve();
  d2.resolve( "abc" );
  d3.resolve( 1, 2, 3, 4, 5 );

src: https://api.jquery.com/jQuery.when/

#3 (just copy-pasted my work in the bike booking system proj)

let promises = [];

    //for each resource id..
    resourceIds.forEach((id) => {
        // use the resource id to get resource data
        var promise = dataService.getResourcesDataById(id).then(resourceData => {  

            var jqxhr = $.getJSON(url, function (slots) {
				//do something  				
            }).fail((jqXHR, textStatus, errorThrown) => {
          		//do something
            });

            return jqxhr;//return promise
        });

        promises.push(promise);

    });


    $.when.apply(null, promises).done(function () {
        //when all promises are resolved do something       
    })
    .fail((jqXHR, textStatus, errorThrown) => {	
		//do something
    });

References:

https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment