2015-09-01 36 views
0

我有两个功能如何让函数initMap()在它的执行之间等待?

function otherfun(val){ 
    var data = {'latitude': val[0], 'longitude': val[1]}; 
    $.post(URL, data, function(response){ 
     if(response){ 
      // I want to return response from here 
     } 
     else{ alert('Error! :('); } 
    }); 
} 


function initMap() { 

     var pos = {}; 
     if (navigator.geolocation) { 

     navigator.geolocation.getCurrentPosition(function(position) { 
     var pos = { 
      lat: position.coords.latitude, 
      lng: position.coords.longitude 
     }; 

     var output = otherfun([pos.lat,pos.lng]); 

     alert(output); 
     // use output's value further 

} 

功能initMap()执行最初。我传递的纬度和经度值来otherfun()

我想:

  1. 返回的从功能otherfun响应的价值。
  2. 使initMap()函数等待otherfun()的返回并存储在变量输出中
  3. 然后显示带有输出值的警报框。

回答

1

在两个函数中分割initMap。原始的init和在otherfun之后调用的回调函数。

function otherfun(val) { 
    var data = {'latitude': val[0], 'longitude': val[1]}; 
    $.post(URL, data, function(response){ 
     if(response){ 
      otherfunCallback(response); // Call a callback function 
     } 
     else{ alert('Error! :('); } 
    }); 
} 

function initMap() { 

     var pos = {}; 
     if (navigator.geolocation) { 

     navigator.geolocation.getCurrentPosition(function(position) { 
     var pos = { 
      lat: position.coords.latitude, 
      lng: position.coords.longitude 
     }; 

     otherfun([pos.lat,pos.lng]); 
} 

// The callback function that alert for the output 
function otherfunCallback(data) { 
    // ... extract the data you need 
    var output = ...; 
    alert(output); 
} 

如果您需要存储输出结果,可以将其保存在变量而不是区域设置中。

相关问题