jQuery延迟循环

I'm trying to call an ajax function for every selected checkbox on a page. Once all of those ajax calls have completed, I want to do something else. In the example below, the 'all calls completed' text is written to the console before any of the 'single call completed' text. How can I make this wait until all ajax calls are finished? Thanks!!

function ajax_function() {
  return $.ajax({
    url: "submit.php",
    type: "POST",
    dataType: "json",
    data: form_data,
    cache: false
  })
}

var deferreds = $('input:checkbox:checked.checkprint').map(function(i, elem) {
  $.when(ajax_function()).then(function(data) {
    console.log('single call completed');
    return data;
  });
});

$.when.apply($, deferreds.get()).done(function() {
  console.log('all calls completed');
});

You can make your ajax calls synchronous.

function ajax_function() {
  return $.ajax({
    url: "submit.php",
    type: "POST",
    dataType: "json",
    data: form_data,
    cache: false,
    async:false
  })
}

option 2:

var totalnumber = $('input:checkbox:checked.checkprint').length;
var counter   = { t: 0 };
var deferreds = $('input:checkbox:checked.checkprint').map(function(i, elem) {
  $.when(ajax_function(totalnumber,counter)).then(function(data) {
    console.log('single call completed');
    return data;
  });
});

function ajax_function(totalnumber,counter) {
  return $.ajax({
    url: "submit.php",
    type: "POST",
    dataType: "json",
    data: form_data,
    cache: false,

  }).done(function( html ) {
    counter.t++;
    if (counter.t == totalnumber) {
         console.log('all calls completed');
    }
  });
}

Why counter.t, because objects are passed as references and we need to change the value of counter.t.

I think I accomplished what I was trying to do using ajaxStop (http://api.jquery.com/ajaxStop/)

$(document).delegate('#submit_all', 'click', function(e) {
  $('input:checkbox:checked.checkprint').each(function() {
    ajax_function();
  });
  $("#submit_all").one("ajaxStop", function() {
    console.log('all calls completed');
  });
});