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

i have this type of situation in my code, now many time function three is called before first and second complete execution and distance value is not updated.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
neeraj bharti
  • 361
  • 1
  • 3
  • 20

1 Answers1

17

Make use of callbacks:

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();
});
Angelo A
  • 2,744
  • 6
  • 28
  • 37
  • 1
    I like this one, had no clue how to use callbacks. Going to research into this, thank you. –  Oct 23 '12 at 12:54
  • 1
    These functions (like yours) are called 'asynchronous functions'. Callbacks prevent other functions from executing before the ansynchronous ones are completed (when used properly). You're welcome. – Angelo A Oct 23 '12 at 13:03