繁体   English   中英

在执行另一个函数之前,如何使jquery等待一个函数完成?

[英]How can I make jquery wait for one function to finish before executing another function?

function test(){
var distance=null;
       first();
       second();
       third();
alert(distance);//it shows null always because it take 2 second to complete.

}
 function first(tolat, tolon, fromlat,fromlon){

// calulating road distance between two points on the map using any other distance caluculating apis. 

distance=dis;  // update the value of distance but it takes 2 second to complete.

}
 function second(){}
 function third(){}

我在我的代码中有这种情况,现在很多时间函数三在第一次和第二次完成执行之前被调用而距离值没有更新。

利用回调:

function first(tolat, tolon, fromlat, fromlon, callback) {
     if (typeof(callback) == 'function') {
        callback(distance);
     }
}

function second() { }
function third() { }

first("vartolat", "vartolon", "varfromlat", "varfromlon", function(distance) {
    alert(distance);
    second();
    third();
});

检查jQuery when()方法。 它会对你有所帮助

暂无
暂无

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

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