17
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回目と2回目の完全な実行の前に関数3が呼び出され、距離の値が更新されないことがよくあります。

4

1 に答える 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();
});
于 2012-10-23T12:47:42.867 に答える