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

18
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(){}

我在代码中遇到了这种情况,现在函数三在第一和第二个函数完成执行之前被多次调用,并且距离值没有更新。


1
检查jQuery的when()函数。http://api.jquery.com/jQuery.when/ - Murali Murugesan
也许你可以从一个函数中调用另一个函数? - intelis
最佳方法完全取决于“任何其他距离计算API”正在执行的操作。 - jbabey
我已从此问题中删除了J标签,因为此问题与J语言无关。请在将来打标签时更加小心。谢谢。 - sepp2k
利用jQuery队列功能的优势。请参阅https://dev59.com/i3NA5IYBdhLWcg3wF5uO - ForOhFor
1个回答

17

利用回调函数:

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

1
我喜欢这个,以前不知道如何使用回调函数。我打算研究一下,谢谢。 - user1372494
1
这些函数(像你的)被称为“异步函数”。回调函数可以防止其他函数在异步函数完成之前执行(如果使用正确)。不客气。 - Angelo A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接