无法在getLocalWeather中获取Geolocation API封装函数getPosition的返回值
问题原因
- 你当前的
getPosition没有显式返回值,默认返回undefined,且navigator.geolocation.getCurrentPosition是回调式异步API,回调函数内部的return不会被外层getPosition捕获作为返回值。 - async/await语法需要等待Promise对象完成才能拿到返回结果,所以你需要把回调式的定位逻辑封装成Promise返回。
修复后的代码
改造getPosition函数
function getPosition() { // 返回Promise对象供async/await调用 return new Promise((resolve, reject) => { if(navigator.geolocation) { navigator.geolocation.getCurrentPosition( // 定位成功时把position通过resolve抛出 (position) => resolve(position), // 定位失败时把错误信息通过reject抛出 (error) => { alert("Sorry, we can't retrieve your local weather without location permission."); reject(error) } ); console.log("Getting the position information...") } else { const errMsg = "Sorry, your browser does not support HTML5 geolocation."; alert(errMsg); reject(new Error(errMsg)) } }) };
改造getLocalWeather调用逻辑
const getLocalWeather = async () => { if(loading === 'loading') return setLoading('loading') try { // 加await等待Promise执行完成拿到定位结果 const position = await getPosition() console.log(position) // 后续调用天气接口的逻辑可写在这里 } catch (err) { // 定位失败的兜底逻辑可写在这里 console.error('定位失败:', err) } finally { // 不管成功失败都更新加载状态 setLoading('done') } };
核心改动说明
- 给
getPosition函数整体返回一个Promise实例,异步操作成功时调用resolve()传递结果,失败时调用reject()传递错误 - 在async函数中调用
getPosition时添加await关键字,等待Promise状态变更后才能拿到返回的定位结果 - 新增
try/catch块捕获定位过程中可能出现的异常,避免页面抛出未捕获错误
内容的提问来源于stack exchange,提问作者Jalen
相关产品推荐
相关产品推荐

