title: How to handle completion of many asynchronous callbacks
body: <p>I have a local WebSQL db that I need to sync with a remote MySQL server. To do so, I have split the process into multiple requests, so I can fire the callback in between every request to show the progress.</p>
  
  <p>The problem is that I have serious race conditions here that I don't think I can solve with the callbacks, because the insert statements are within a $.each() function (aka for loop).</p>
  
  <p>I have this asynchronous problem spread all over the database interface. I have been investigating how to use promises and Deferred in jQuery, but that doesn't seem to solve the problem. I just need to make this thing synchronous.</p>
  
  <pre><code>evalua.webdb.sync = function(callback){ 
  $.getJSON("index.php/get/sync_riesgo",function(data){
      evalua.webdb.db.transaction(function(tx){
          $(data.riesgos).each(function(index, value){
              tx.executeSql('INSERT INTO riesgos (idRiesgo, nombre) VALUES ("'+value.idRiesgo+'", "'+value.nombre+'")');
          });
          $(data.estancias).each(function(index, value){
              tx.executeSql('INSERT INTO estancias (idEstancia, nombre, dimensionMinima) VALUES ("'+value.idEstancia+'", "'+value.nombre+'", "'+value.dimensionMinima+'")');
          });
          $(data.riesgosestancias).each(function(index, value){
              tx.executeSql('INSERT INTO riesgosestancias (idRiesgoEstancia, idRiesgo, idEstancia, porcentaje, indispensable) VALUES ("'+value.idRiesgoEstancia+'", "'+value.idRiesgo+'", "'+value.idEstancia+'", "'+value.porcentaje+'", "'+value.indispensable+'")');
          });
      });
  });
      callback("First one done");
  $.getJSON("index.php/get/sync_operaciones",function(data){
      evalua.webdb.db.transaction(function(tx){
          $(data.companhias).each(function(index, value){
              tx.executeSql('INSERT INTO companhias (idCompanhia, nombre) VALUES ("'+value.idCompanhia+'", "'+value.nombre+'")');
          });
          $(data.operaciones).each(function(index, value){
              tx.executeSql('INSERT INTO operaciones (idOperacion, nombre, descripcion) VALUES ("'+value.idOperacion+'", "'+value.nombre+'", "'+value.descripcion+'")');
          });
      });
  });
      callback("Second one done");
  }
  </code></pre>