Guarantee the order of code execution - How to??

You must Login before you can answer or comment on any questions.

How do you synchronise events in appcelerator? For example if I have a function which contains some AJAX calls:

ajax_function(); // << This function has 2 or 3 seperate ajax calls
 
alert("All AJAX comms completed!");
How do you re-write this, so that the alert happens AFTER ALL AJAX callbacks have completed??

2 Answers

Accepted Answer

It's tricky. One way of solving it is by having a counter:

(this code is totally on the top of my head not tested probably buggy, but I've used the approach with success before)

var numCalls = 5; // or whatever amount of Ajax calls you make
var callCounter = 0;
 
for(var i = 0; i < numCalls; i++) {
    // Let's pretend we have a callAjax function doing all the boring Ti.Network stuff and we just supply it with the callback
    callAjax(function() {
        // Doing exciting relevant stuff here, and then...
        callCounter++;
        if(callCounter === numCalls) {
            // Last call
            alert('The end is nigh');
        }
    });
}
If you do not know the amount of calls you do up front (perhaps because of recursive calls or other stuff), you can set numCalls to 0 in the beginning and increment it when you start each call. The problem with this approach, though, is that you might get into a situation where all current requests have gotten a response back but there are still additional requests waiting to be sent out, meaning that you can't be sure if you're really at the very end.

You have to ways: - working with events - working with callbacks

It depends of use case.

Your Answer

Think you can help? Login to answer this question!