title: Jquery : control function flow with deferred
body: <p>Apologies but I seem to be going round in circles.</p>
  
  <p>The process is fairly staightforward</p>
  
  <ol>
  <li><p>SaveButtonClicked</p></li>
  <li><p>call function to perform offline db transaction to update a record</p></li>
  <li><p>check if online ( /*used the Ed Norton example for doing this */ )</p></li>
  <li><p>if online call select transaction to fetch all updated records</p></li>
  <li><p>success of select load results into an array</p></li>
  <li><p>call webservice with array</p></li>
  </ol>
  
  <p>so far I've tried to control the flow with 
  $.Deferred, dothis = defer.pipe(...), 
  .queue [but these seem to based on an element rather than a function completing] , 
  putting the functions into an array ,</p>
  
  <p>in testing the console always writes the 'array built' before the 'building array' </p>
  
  <pre><code>var arrvals = [];
  var deferA , deferB;
  function updatedb(params){
      db.transaction('update....',[params],updateOk,updateFail)
  }
  function updateOk(){
      deferA.resolve()
  }
  function updateFail(){
      deferA.reject()
  }
  function areweonline(){
      $.ajax(.....) 
  }
  function selectrows(){
      db.transaction('update....',[params],buildarray,selectFail)
  }
  function buildarray(transaction,results){
      console.log('building array')
      for(i=0;i&lt;=results.rows.length;i++){
          var row = results.rows.item(i);
          var job = {};
          job.text = row["testtext"]
          arrvals.push(job);
      }
      deferB.resolve()
  }
  function selectFail(){
      deferB.reject();
  }
  function callwebservice(vals){
      $.ajax(....) /* this bit is working fine*/
  }
  function SaveButtonClicked(){
      deferA = $.Deferred(); 
      deferB = $.Deferred();
      $.when(deferA).then(
          console.log('update completed')
          $.when(deferB).then(function(){
              console.log('array built')
              callwebservice(arrvals)
          })
      )
  }
  </code></pre>
  
  <p>So what would be the best approach? $.Deffered, queue, callback ...dark magic?</p>