1

I am trying to make a time conversion tool, first thing it does is gets the co-ordinates of both the cities you enter and then calculates time accordingly.

But the problem I am facing is that the function which gets the co-ordinates takes some time and it is asynchronous as well and thus there are issues with the execution order.

Is there are a way I can make sure that execution of a next statement gets done one after the previous completes?

function initializeConversion() { //Gets the date from non hidden fields and converts it to the format which is required if (document.getElementById('datenh1').value.length == 0) //Finds the non-empty field setValueOfDateTwo(); else setValueOfDateOne(); //Get the value from the fields cityOneString = document.getElementById('city1').value; cityTwoString = document.getElementById('city2').value; //Logging Statements console.log("City 1: "+cityOneString); console.log("City 2: "+cityTwoString); //Gets the coordinates of both cities //This is where the issue is getCoordinates(cityOneString); getCoordinates(cityTwoString); } 

You can check the whole code here on github: https://github.com/udit96rc/TimeConverter

You can check the tool here: http://uditchugh.me/pt

2
  • 1
    Give Promise a try. Commented Jun 23, 2015 at 9:28
  • @Leo Yeah. Was reading about it. Will use it next time. Commented Jun 23, 2015 at 9:32

1 Answer 1

1

In getCoordinates you use asynchronous request to Google API via geocoder.geocode() call. The second argument in this method is an actual callback which is executed when the request is done. Pass own callback function to getCoordinates function (as a second argument) and call it once the actual request is finished processing.

function getCoordinates(city, callback) { ... geocoder.geocode({ address: address }, function(results, status) { ... if (typeof callback === 'function') callback(); }); } getCoordinates(cityOneString, function() { getCoordinates(cityTwoString); }); 
Sign up to request clarification or add additional context in comments.

3 Comments

Can you please show the change here? I am pretty new to JavaScript. Thanks in advance.
Thanks a lot. Will try this and get back soon.
Yes. Saw it already and implemented it as well. It works. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.