Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Javascript Callback or counter

Posted on 2014-04-08
3
Medium Priority
?
394 Views
Last Modified: 2014-05-29
I have a working Google API geocoder that looks up the name of a county that a city is in and then puts the resulting list of counties into a new array.
However when testing I see that sometimes the order in which the counties are returned is different. I suspect what is happening is that all of the requests are being sent one right after the other but the API has different servers processing so sometimes the first city sent is the last one returned.  - is there a way to make this sequential? - this is a minor issue as I could just rebuild the address array in the order of returned values - just curous as to why it does what it does now.

The other issue i have is that if I have a long list of addresses the script moves ahead to my do something new part of the code before it finishes getting all of the address.

Do I need a callback or some type of counter to ensure that it gets all the responses before moving ahead?



<div id='myInfo1'>-</div>
<div id='myInfo2'>-</div>

$(document).ready(function () {
    var counties = [];
    var addresses = ["Orlando, Florida", "Boone,Iowa", "Ames,Iowa", "Des Moines,Iowa", "Jefferson,Iowa"];

    addresses.forEach(function (entry) {
        var myAddress = entry;
        var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=" + myAddress + "&sensor=true";
        console.log(geocodingAPI);
        $.getJSON(geocodingAPI, function (json) {
            $.each(json.results[0].address_components, function (i, jsonData) {
                level = jsonData.types[0];
                if (level.toLowerCase() == 'administrative_area_level_2') {
                    county = jsonData.short_name.substring(0, jsonData.short_name.length - 7);
                    counties.push(county);

                    console.log(counties.toString());
                    $('#myInfo1').html(counties.toString());
                    $('#myInfo2').html(counties.length);
                }

            });
        });
    });

});

//now do something with those results after all are received.

Open in new window

0
Comment
Question by:lvmllc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 44

Expert Comment

by:Chris Stanyon
ID: 39987189
The reason they may come back out of sequence is simply down to the nature of AJAX calls. You make an AJAX call for each address in your list, but because the AJAX call is asynchronous, it doesn't wait around to finish before starting the next one. It may just be that the request for the first address takes slightly longer at the server than the request for the second request.

As for your code continuing to run - exactly the same reason as above - you make your calls Asynchronously, so your code doesn't stop and wait for the responses - it just carries on.

Normally, if you want to run code after the AJAX has finished, you make use of the 'Success' argument or .done() method

If you absolutely need your data returned 'in order' and only continue on with your code after all requests have finished, then you may have to change your AJAX request to a Synchronous one - the downside being it locks the browser while it's working.

As far as I'm aware there isn't a native callback mechanism for Google Geocoding
0
 

Author Comment

by:lvmllc
ID: 39987409
Chris - let me try something with the .done() method - I'll post back tomorrow on what I figure out along with any question I might still have for you.
0
 
LVL 49

Accepted Solution

by:
Roonaan earned 2000 total points
ID: 40056953
The forEach method actually provides a second argument, which is the original index in the array.

Using that, you could insert the response in the same index as the addresses:

$(document).ready(function () {
    var counties = [];
    var addresses = ["Orlando, Florida", "Boone,Iowa", "Ames,Iowa", "Des Moines,Iowa", "Jefferson,Iowa"];

    addresses.forEach(function (entry, index) {
        //                             ^---- Use index argument from original array
        var myAddress = entry;
        var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=" + myAddress + "&sensor=true";
        console.log(geocodingAPI);
        $.getJSON(geocodingAPI, function (json) {
            $.each(json.results[0].address_components, function (i, jsonData) {
                level = jsonData.types[0];
                if (level.toLowerCase() == 'administrative_area_level_2') {
                    county = jsonData.short_name.substring(0, jsonData.short_name.length - 7);
                    counties[index] = county; //  INSERT AT ASSOCIATED INDEX

                    console.log(counties.toString());
                    $('#myInfo1').html(counties.toString());
                    $('#myInfo2').html(counties.length);
                }

            });
        });
    });
});

Open in new window

0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question