我在Callback 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
}
},
答案 0 :(得分:2)
以下是我在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);
}
答案 1 :(得分:0)
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重复检查该标志,并将继续调用该函数,直到设置该标志。