gpt4 book ai didi

javascript - 回调 hell 、地理位置 - JavaScript

转载 作者:行者123 更新时间:2023-12-02 18:06:03 25 4
gpt4 key购买 nike

我正处于回调 hell 中,我真的不知道如何摆脱它。我尝试阅读其他涉及该主题的主题,但我仍然不明白这个概念。

我正在使用 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
}
},

最佳答案

这是我在 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);
}

关于javascript - 回调 hell 、地理位置 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20097933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com