title: jQuery JavaScript Nested Asynchronous Functions callback
body: <p>I'm a little confused how to determine when async function called multiple times from another one is finished a call from the last iteration:</p>
  
  <pre><code>function MainAsyncFunction(callback) {
    for (var i = 0; i &lt; 10; i++) {
      SubAsyncFunction(function(success) {
        if (i &gt;= 10 &amp;&amp; success) { // THIS IS WRONG?!
          callback(true); // happens too early
        }
      });
    }
  };
  
  function SubAsyncFunction(callback) {
    SubSubAsyncFunction(function() {
          callback(true);
    });
  }
  </code></pre>
  
  <p>What I'm doing is calling the <a href="https://developers.google.com/maps/documentation/javascript/distancematrix#distance_matrix_requests" rel="nofollow">Google Distance Matrix service</a>, which has a limitation of 25 destinations, hence I'm having to split my array of destinations to call this service multiple times but I don't understand when it's finished.</p>
  
  <p>and in the main bit of code I can tell that the second iteration of the loop in the <em>MainAsyncFunction</em> hasn't yet completed when it does a call back.</p>
  
  <p>I think my problem is I haven't got my head around the order of events when dealing with Async functions in JavaScript... please explain how the subject is normally achieved.</p>