How should I execute functions only one after another in JavaScript?

223 views Asked by At

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

1

There are 1 answers

3
VisioN On BEST ANSWER

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);
});