Javascript 如何从承诺中获得结果价值?
我在获取promise函数返回的地理位置坐标时遇到问题。我使用的代码如下所示: 我试过:Javascript 如何从承诺中获得结果价值?,javascript,geolocation,es6-promise,Javascript,Geolocation,Es6 Promise,我在获取promise函数返回的地理位置坐标时遇到问题。我使用的代码如下所示: 我试过: export const getGeolocation = () => { return getPosition().then(result => return result) } // doesnt work 有人能向我解释一下从承诺中获得价值的正确方法是什么吗?谢谢,试试这个 const getPosition=()=>{ 返回新承诺((res,rej)=>{ navigator.g
export const getGeolocation = () => {
return getPosition().then(result => return result)
} // doesnt work
有人能向我解释一下从承诺中获得价值的正确方法是什么吗?谢谢,试试这个
const getPosition=()=>{
返回新承诺((res,rej)=>{
navigator.geolocation.getCurrentPosition(res,rej)
});
}
const getGeolocation=async()=>{
试一试{
让结果=navigator.permissions.query({
名称:“地理位置”
});
如果(result.state==“已授予”){
让response=等待getPosition();
}否则{
抛出新错误(“用户拒绝地理定位”);
}
}捕获(错误){
console.log(错误消息);
}
}
getGeolocation()
您需要在getGeolocation()
函数中使用Callback方法,而不是return
getGeolocation((result)=>{
console.log("Position : ",result);
});
以下是您的解决方案:
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);
}
});
要了解回调如何工作,请通过下面的链接,你会有一个更好的想法
这是否回答了您的问题。也许更好: