title: How to make javascript hold until a function returns a value and then proceed to the next line?
body: <p>I am calculating the driving distance between two points and then alert them. </p>
  
  <p>however calculating the distance method takes like 2 seconds to proceed. </p>
  
  <p>so when i click on the button that alerts the value of the distance the value is null. </p>
  
  <p>if i clicked again it shows the value of the distance. </p>
  
  <p>I am trying to make the code hold until a value is returned from the calculating function: </p>
  
  <p>here is part of my code:</p>
  
  <pre><code> function calculate(cb){
  if(!checkSelected()){return false;}
  
  
      MQA.withModule('directions', function() {
  
      /*Uses the MQA.TileMap.addRoute function (added to the TileMap with the directions module)
      passing in an array of location objects as the only parameter.*/
      map.addRoute([
        {street: addr_s[1]  , city: addr_s[2] , state:addr_s[3] , postalCode: addr_s[4]},
        {street: addr_d[1], state: addr_d[2] , state:addr_d[3] , postalCode: addr_d[4]}
      ]);
  
    });
  
      MQA.withModule('directions', function() {
  
        /*Executes the route call with 4 parameters.*/
        MQA.Directions.route(
  
          /*An array of location objects as the first parameter.*/
          [{ street: addr_s[1]  , city: addr_s[2] , state:addr_s[3] , postalCode: addr_s[4]},
          { street: addr_d[1], state: addr_d[2] , state:addr_d[3] , postalCode: addr_d[4] }],
  
          /*An object for route options are the second parameter.
          In this case, we are not using any options so we pass in null.*/
         {routeOptions:{routeType:'SHORTEST', avoids:['ferry']}},
  
          /*You can pass in an instance of MQA.TileMap for the third parameter. If not null, the call will create
          a route ribbon on the map. Again, we are not using a map in this example so we pass in null.*/
  
   null,
          /*The fourth parameter is the callback function to be executed after the route call. The callback
          will pass the raw response from the route request as a parameter.*/
          cb
        );
    });
  
  
     }
  
     function work(){
    calculate(function (data){
  
    if(data.route) {
  
      var distance = data.route.distance;
       var time = data.route.time;
       time_minutes = time/60 ;
       document.forms["myform"]["distance"].value =distance;
        document.forms["myform"]["time"].value =time_minutes ;
  
      }
    });
  }
  </code></pre>