简体   繁体   English

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

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

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 您可以在github上查看整个代码: https : //github.com/udit96rc/TimeConverter

You can check the tool here: http://uditchugh.me/pt 您可以在此处检查该工具: http : //uditchugh.me/pt

In getCoordinates you use asynchronous request to Google API via geocoder.geocode() call. getCoordinates您可以通过getCoordinates geocoder.geocode()调用对Google API的异步请求。 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. 将自己的回调函数传递给getCoordinates函数(作为第二个参数),并在实际请求完成处理后调用它。

function getCoordinates(city, callback) {
   ...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM