Calling request in the callback of a previous call
<p>My issue is that I want to loop through an array and retrieve JSON data about each item and then populate it.  I know that the below way does not work, because it will cycle through each 'n' before the first response is ever receieved.</p>

<p>What makes sense for me to do is to call the request again in my call back function.  So, after the first response is received it will make a call to get a second response... etc, etc.</p>

<p>Can anyone help me with how I would go about doing something like this?   The end goal is populate each array item with the appropriate response.  I'm new to programming, so this is a little complicated for me.</p>

<pre><code> function getDistance() {

    for (n in addresses()) {
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
              origins: [clientLocation()],
              destinations: [addresses()[n].position()],
              travelMode: google.maps.TravelMode.DRIVING,
              unitSystem: google.maps.UnitSystem.IMPERIAL,
              avoidHighways: false,
              avoidTolls: false
          }, callbackFunction);
    }



function callbackFunction (response, status) {
    addresses()[n].distanceText(response.rows[0].elements[0].distance.text)
    addresses()[n].distanceValue(response.rows[0].elements[0].distance.value)              
    //get the next one??

};  
</code></pre>

<p>}          </p>

<p>P.S. I know that I should be sending an array to Distance Matrix Service, and I will, but I want to figure out this problem generally because it presents itself often.</p>

<p>P.P.S.  I'm using knockout.js hence the addresses()[n] call.</p>

<p>Thank you.</p>
