title: Javascript Asynchronous success function - mutex
body: <p>consider the following situation:</p>
  
  <p>In order to have lots of work processed at my backend I send data to an interface and wait for the resulting data to return. Therefore ajax calls are just perfectly. Because of not knowing, in what order the result is received, and I need the results in specific order <em>before</em> I can display anthing, I will have a function only be called, if all sent tasks where returned correctly. This could be done through a simple (reduced, not exactly) semaphore variable that counts how many tasks were sent.</p>
  
  <pre><code>    var tasks = 0;
  
      do {
      // things to prepare
      tasks++;
  
      $.post("foo.php",data, function(data) {
      tasks--;
      foo(data); 
  });
  
      }while(thereIsMore);
  
      foo(data) {
  
      // push data to array
      // sort the array
  
      if(tasks == 0)
       processResults(array);
  
      }
  </code></pre>
  
  <p>Javascript is called to be single tasked, not multi tasked.
  Am I really right to say, that there cannot be any situation to have mutual exclusion on accessing the array and the tasks counter because it will never happen?
  I am a bit confused of the asynchronous behaviour and may think of scenarios where racing situation could be given?</p>
  
  <p>An example (and what my understanding is):</p>
  
  <p>3 Tasks where sent out and received in a very small time frame.
  All responses are handled therefore in a type of scheduling. 
  Task 1 has checked (if tasks==0) and it was false. Task 2 is paused one instruction before checking the tasks and task 3 is now executed as success handler. Task 3 now decrements tasks and its value is 0. Task 3 is paused and Task 2 is resumed. Task 2 checks if(tasks==0) and hell yeah.. it is zero. It starts processing, but not all data is in the array and sorted.</p>
  
  <p>I am very interested in your opinion or knowledge, if this is totally insane sh*t that is not possible to happen. Share your knowledge please :-)</p>