我有两个功能
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() 最初执行。我将 lat 和 lng 的值传递给 otherfun()
我想要:
- 返回函数 otherfun 的响应值。
- 使 initMap() 函数等待 otherfun() 返回并存储在变量输出中
- 然后显示带有输出值的警报框。
最佳答案
将 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);
}
如果您需要存储输出结果,您可以将其保存在变量而不是语言环境中。
关于javascript - 如何让函数 initMap() 在其执行之间等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32326247/