简体   繁体   English

在继续之前完成功能的执行

[英]Finish function executing before proceeding

I have a form that is validated upon submission, inside the form submit a function is called, the submit continues and doesn't wait for the function to finish. 我有一个在提交时经过验证的表单,在表单内部提交了一个函数,该提交继续,并且不等待函数完成。 How do I fix this? 我该如何解决?

var clientaddress=false;

function checkaddress(callback){
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function(results, status) {
        if (status != google.maps.GeocoderStatus.OK) {
            clientaddress=false;
             callback(false);
        }
       else if (status == google.maps.GeocoderStatus.OK) {
            clientaddress=true;
            callback(false);
       }
    }

 jQuery(document).ready(function(){
     jQuery("#submitOrder").submit(function(){
        checkaddress(function(result) {

                    if (!result) { 
                        jAlert("Please enter a valid address!");
                        jQuery("#address").focus();
                        isValidation = 0; 

                    }
                });

       //other validation code that gets executed without waiting for checkaddress()
       //submit page
     })

I tried to make one function that calls both the address checker and a validation function, but still they do not wait for each other. 我试图使一个函数同时调用地址检查器和验证函数,但是它们仍然不会彼此等待。

How can I solve this problem? 我怎么解决这个问题?

Because the geocode function is async! 因为geocode功能是异步的! Use a callback: 使用回调:

function checkaddress(callback){
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) { 
        if (status != google.maps.GeocoderStatus.OK) {
            callback(false)
        } else if (status == google.maps.GeocoderStatus.OK) {
            callback(true)
        }
    });
}

Then use this like: 然后像这样使用:

checkaddress(function(result) {
    if (result) { 
        //result true! 
    } else { 
        //result false! 
    }

    //REST OF YOUR CODE GOES HERE, IF PUT OUTSIDE IT WILL EXECUTE WHILE CHECKADDRESS IS IN PROGRESS
});

Your submit function is also most likely running the default behavior, use preventDefault 您的submit函数也很有可能正在运行默认行为,请使用preventDefault

jQuery("#submitOrder").submit(function(e){
    e.preventDefault(); 
    //code
});

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

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