如何从承诺中获得结果价值?

问题描述 投票:0回答:2

我无法从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

有人可以向我解释从承诺中获得价值的正确方法是什么?谢谢

javascript geolocation es6-promise
2个回答
1
投票

您需要使用[[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); } });

要了解回调的工作原理,请通过下面的链接,您将会有更好的主意。

https://www.w3schools.com/jquery/jquery_callback.asp


0
投票
尝试一下。

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();
© www.soinside.com 2019 - 2024. All rights reserved.