Javascript: Set the order of functions
<p>I'm writing a titanium app but I'm having an issue with the execution order of my javascript.</p>

<p>I have an event listener on a button. It's a reload button that clears a table, uses HTTPClient to GET a JSON array of 'appointments', saves each appointment, and refreshes a table list. The problem is I am executing the table delete first which should clear the table, then I get the appointments but when the app refreshes the datatable it's like it's doing it too soon and the new appointments haven't been saved yet because I'm getting an empty list. Now if I comment out the db.deleteAll line, each time I click reload the list is refreshed with the new (and existing) appointment data.</p>

<p>I need to make sure everything is done in order and only when the previous task is dfinished. So appointments.download() has to be executed AFTER db.DeleteAll and the list refresh has to be executed AFTER var allAppointments = db.All();</p>

<p>I think the problem is that the appointments.download() function has to make a HTTP GET call and then save the results and the other functions are not waiting until it's finished. </p>

<p>Here is the code:</p>

<pre><code>btnReload.addEventListener('click', function(e){
    var affected = db.deleteAll();
    appointments.download();
    var allAppointments = db.all();
    Ti.API.info(allAppointments);
    appointmentList.setData(allAppointments);
});
</code></pre>

<p>Here are the functions that are being called:</p>

<p>db.deleteAll():</p>

<pre><code>api.deleteAll = function(){
    conn.execute('DELETE FROM appointments');
    return conn.rowsAffected;
}
</code></pre>

<p>appointments.download():</p>

<pre><code>var appointments = (function() {
    var api = {};
    api.download = function(){

        var xhr = Titanium.Network.createHTTPClient();
        xhr.onload = function()
        {
          var data = JSON.parse(this.responseText);
          var dl = (data.length);
          for(i=0; i&lt;dl;i++)
          {
            //p = addRow(data,i); // returns the **arr array 
            //Ti.API.info('Saving : '+data[i].first_name);
            var contact_name = data[i].first_name + ' ' + data[i].last_name;
            var start_date = data[i].start_date;
            var reference = data[i].reference;
            var comment = data[i].comment;
            var appointment_id = data[i].quote_id;

            var lastid = db.create(appointment_id, start_date, reference, contact_name, comment);
            //Ti.API.info(lastid);
          }

        };
        xhr.open('GET','http://********.co.uk/appointments/download/');
        xhr.send();

        return;
}
</code></pre>

<p>Any help most appreciated!
Billy</p>
