gpt4 book ai didi

javascript - 如何让 jquery 在执行另一个函数之前等待一个函数完成?

转载 作者:可可西里 更新时间:2023-11-01 01:23:14 25 4
gpt4 key购买 nike

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

关于javascript - 如何让 jquery 在执行另一个函数之前等待一个函数完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13030639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com