如何在JavaScript中一个接一个地执行函数?

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

我正在尝试制作一个时间转换工具,它首先会获取您输入的两个城市的坐标,然后相应地计算时间。

但我面临的问题是获取坐标的函数需要一些时间,而且它也是异步的,因此执行顺序存在问题。

有没有一种方法可以确保下一条语句的执行在前一条语句完成之后完成?

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

您可以在 github 上查看完整代码: https://github.com/udit96rc/TimeConverter

您可以在此处查看该工具:http://uditchugh.me/pt

getCoordinates 中,您使用异步请求通过 geocoder.geocode() 调用 Google API。此方法中的第二个参数是一个实际的回调,它在请求完成时执行。将自己的回调函数传递给 getCoordinates 函数(作为第二个参数),并在实际请求处理完成后调用它。

function getCoordinates(city, callback) {
   ...

   geocoder.geocode({ address: address }, function(results, status) {
       ...
       if (typeof callback === 'function')
           callback();
   });
}

getCoordinates(cityOneString, function() {
    getCoordinates(cityTwoString);
});