您需要使用回调方法代替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);
}
});
要了解回调的工作方式,请通过下面的链接,您将会有一个更好的主意。
https://www.w3schools.com/jquery/jquery_callback.asp
,
尝试一下。
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();
本文链接:https://www.f2er.com/2727864.html