【问题标题】:Callback Hell, Geolocations - JavaScript回调地狱,地理位置 - JavaScript
【发布时间】:2013-11-20 13:58:40
【问题描述】:

我在回调地狱,我真的不知道我将如何摆脱它。 我已经尝试阅读其他涉及该主题的主题,但我仍然没有掌握这个概念。

我正在使用 Google Maps API v3,我正在尝试返回用户当前位置,以便我可以继续将其传递给其他方法。

我已经通过脱离上下文使用 jQuery .done() 成功了,它会引发警告,但我设法获得了我的坐标对象。

如果我调用 userPosition,如何让该方法在返回变量 userPosition 之前等待 findUser 方法?

编辑:上传错误的代码,编辑后缩进很烂。 :)

userPosition: function(position)
            {
                 if (typeof position === 'undefined') 
                 {
                      //Call on findUser, when ready callback it self to set variables
                 } 
                 else 
                 {
                     //var userPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                     //return userPosition;
                 }
            },

findUser: function()
                {
                    var self = this;
                    if (navigator.geolocation)
                    {
                        navigator.geolocation.getCurrentPosition(
                            function(position) { // If successful
                                self.userPosition(position);
                            }, 
                            function(e) { // If something went wrong
                                var errors = {
                                    1: 'Permission denied',
                                    2: 'Position unavailable',
                                    3: 'Request timeout'
                                };
                                alert("Error: " + errors[e.code]);
                            },
                            { enableHighAccuracy: true, timeout: this.timeoutVal, maximumAge: 0 }
                        );
                    }
                    else
                    {
                        // Set flag
                    }
                },

【问题讨论】:

  • 如果位置未定义,您是否尝试访问其coords 属性? userPosition 返回局部变量,但调用 userPosition 不使用返回值?您确定此代码执行您认为的操作吗?
  • 如果我调用 findUser,则上面发布的 userPosition 方法有效。我想要做的不是调用 findUser,而是调用 userPosition,如果 userPosition(position) 未定义,则调用方法 findUser 并在回调上设置 var userPosition 并返回它。这样我就可以调用另一个方法,比如 showUser,它根据坐标在地图上绘制一个标记。
  • 我不明白它是如何工作的。如果position 未定义,那么尝试访问position.coords 应该会引发ReferenceError。编辑:代码已更改;)
  • 抱歉,现在修好了,这更像是我想要的样子。如果我跳过整个 if-typof,那么它会在我调用 findUser 时起作用。

标签: javascript jquery api callback geolocation


【解决方案1】:

这是我在jsfiddle 中的做法。

var thing = {

  findUser: function (callback) {
    var _this = this;

    // use the getPos method to get the geolocation
    this.getPos(function (position) {
        var lat, lng, userPos;
        lat = position.coords.latitude;
        lng = position.coords.longitude;

        // add the new lat lng to the userPosition variable
        _this.userPosition = new google.maps.LatLng(lat, lng);

        // invoke the callback
        callback();
    });
    return this;
  },

  getPos: function (callback) {
    var geo = navigator.geolocation;
    if (geo) {

        // get the geolocation and pass it back to findUser
        geo.getCurrentPosition(callback);
    }
    return this;
  }
}

// if userPosition doesn't exist then grab the geolocation
if (!thing.userPosition) {
  thing.findUser(function () {
    console.log(thing.userPosition);
  });
} else {
  console.log(thing.userPosition);
}

【讨论】:

    【解决方案2】:
    var isUserLocationSet = false;
    userPosition: function(position){
    
                    if(!isUserLocationSet)
                    {
                        settimeout(userPosition, 200);
                        return;
                    }
                    if (typeof position === 'undefined') 
                    {
                        var userPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                        return userPosition;
                    }
                    console.log(typeof position);
                },
    
    findUser: function(){
                //set isUserLocationSet to true on completion in this method
                var self = this;
                if (navigator.geolocation)
                {
                    navigator.geolocation.getCurrentPosition(
                        function(position) { // If successful
                            self.userPosition(position);
                        }, 
                        function(e) { // If something went wrong
                            var errors = {
                                1: 'Permission denied',
                                2: 'Position unavailable',
                                3: 'Request timeout'
                            };
                            alert("Error: " + errors[e.code]);
                        },
                        { enableHighAccuracy: true, timeout: this.timeoutVal, maximumAge: 0 }
                    );
                }
                else
                {
                    // Set flag
                }
            }
    

    在这里,您将使用 settimeout 重复检查该标志,并将继续调用该函数,直到设置该标志为止。

    【讨论】:

    • 是的,这可以工作,但我宁愿依赖纯回调而不是设置 setTimeout。还是谢谢你。
    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2017-04-06
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多