我已经尝试了一段时间了。我有三个功能都可以独立工作。但是,我无法从中获取值getUserCoordinates()
出现在中fetchCurrentTemp()
。undefined
无论我尝试什么,它都会返回。我已经离开JS环境一分钟了,所以也许我错过了一些明显的东西,但是我很沮丧。
fetchCurrentTemp()
import { getUserCoordinates } from './helpers';
const url = 'http://api.openweathermap.org/data/2.5';
export const fetchCurrentTemp = async () => {
const coordinates = getUserCoordinates();
console.log('coords:', coordinates);
// logs 'undefined'
try {
let response = await fetch(`${url}/weather?APPID=x&lat=50.7498752&lon=-100.0004158&units=imperial`);
let output = await response.json();
} catch (error) {
console.log(error);
}
};
getUserCoordinates()
export const getUserCoordinates = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(({ coords }) => {
console.log(coords);
//returns a value
return coords;
});
} else {
alert('Something is wrong');
}
};
应用程式
import React from 'react';
import { fetchCurrentTemp } from './utils/api_calls';
function App() {
return (
<div>
<button onClick={() => fetchCurrentTemp()}>Hello</button>
</div>
);
}
调用时return coords
,您只是从回调函数中退出,而不是退出getUserCoordinates()
。
您可以使用基于Promise的方法,因为它getCurrentPosition
是异步的:
export const getUserCoordinates = () => {
return new Promise((resolve, reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(({ coords }) => {
console.log(coords);
resolve(coords);
});
} else {
reject('Something is wrong');
}
});
};
然后修改fetchCurrentTemp()
为包括await
:
// --snip--
const coordinates = await getUserCoordinates();
// --snip--
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句