Как я могу заставить jquery ждать завершения одной функции перед выполнением другой функции?
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
Использовать обратные вызовы:
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();
});
Ответ 2
Проверить jQuery когда(). Это поможет вам