我无法从promise函数返回地理位置坐标。我正在使用下面的代码,从这里开始:How geolocation.getCurrentPosition return value?
const getPosition = () => {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej)
});
}
export const getGeolocation = () => {
getPosition().then(console.log)
}
我尝试过:
export const getGeolocation = () => {
return getPosition().then(result => return result)
} // doesnt work
有人可以向我解释从承诺中获得价值的正确方法是什么?谢谢
您需要使用[[Callback方法代替return
函数中的getGeolocation()
。
export const getGeolocation = (callback) => {
getPosition().then((result) => {
callback(result);
})
}
现在请看下面的代码来访问来自getPosition()
函数的结果。
getGeolocation((result)=>{ console.log("Position : ",result); });
请检查下面的代码,希望它对您和您都有用
const getPosition = () => { return new Promise((res, rej) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(res); } else { rej("Unable to found current location"); } }); } export const getGeolocation = (callback) => { getPosition().then((result) => { callback({ code: 1, message: "Location", location: result }); }).catch((_error) => { callback({ code: 0, message: _error }); }); } getGeolocation((response) => { if (response.code == "1") { console.log(response.location); } else { console.log(response.message); } });
要了解回调的工作原理,请通过下面的链接,您将会有更好的主意。
const getPosition = () => {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej)
});
}
const getGeolocation = async() => {
try {
let result = navigator.permissions.query({
name: 'geolocation'
});
if (result.state == 'granted') {
let respnse = await getPosition();
} else {
throw new Error("User denied Geolocation");
}
} catch (error) {
console.log(error.message);
}
}
getGeolocation();