javascript - 如何让函数 initMap() 在其执行之间等待?

标签 javascript jquery ajax google-maps google-maps-api-3

我有两个功能

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

我想要:

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

最佳答案

将 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/

相关文章:

javascript - 在没有 GUI/X session 的情况下使用 GreaseMonkey 脚本运行 Firefox 的任何方法

javascript - 如何重置 'no' 上的调查问卷

javascript - 如何将用户从 servlet 重定向到登录页面?

javascript - rails 4 : changing link style upon Ajax call

php - 验证码在 localhost 上工作正常,但不能在线工作

Javascript 数据表分页和自定义属性得到不需要的 trim 字符串

javascript - 来自 Json 的 Google 图表 "undefined is not a function"

javascript - 选中复选框ID ="checkAll"时如何清除所有复选框?

javascript - 使用 jQuery 时提交多次执行的函数

javascript - 如何从表单输入 type=radio 获取值?