2015-09-01 35 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); 
} 

如果您需要存儲輸出結果,可以將其保存在變量而不是區域設置中。

相關問題