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

如何在JavaScript中一个接一个地执行函数?,javascript,asynchronous,synchronous,Javascript,Asynchronous,Synchronous,我正在尝试制作一个时间转换工具,它做的第一件事是获取你输入的两个城市的坐标,然后据此计算时间 但我面临的问题是,获取坐标的函数需要一些时间,而且它也是异步的,因此执行顺序存在问题 有没有办法确保下一条语句的执行在上一条语句完成后一条语句完成 function initializeConversion() { //Gets the date from non hidden fields and converts it to the format which is required

我正在尝试制作一个时间转换工具,它做的第一件事是获取你输入的两个城市的坐标,然后据此计算时间

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

有没有办法确保下一条语句的执行在上一条语句完成后一条语句完成

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上查看整个代码:


您可以在这里检查工具:

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

你能把零钱给我看看吗?我对JavaScript非常陌生。提前谢谢。非常感谢。我会试试这个,然后很快回来。已经看到了它,并且也实现了它。它起作用了。再次感谢。请尝试一下。@Leo是的。我正在读关于它的书。下次我会用的。