【发布时间】:2020-03-31 16:14:15
【问题描述】:
我试图在调用 Geolocation API 后将用户的当前城市加载到页面上。但是,调用 geolocation 函数的主要组件是在 Promise of location 返回之前将 state 设置为 undefined。
我的目标是使用用户的当前位置设置状态。但是,当我在 React 组件中调用 geolocate() 时, state.city 被设置为未定义,因为它不等待地理定位函数返回任何内容。
我的地理定位功能:
const geolocate = async () => {
if (!navigator.geolocation) {
alert('Geolocation is not supported by your browser. Please search for a location to look for weather');
} else {
getCoordinates().then((position) => {
getCityByCoords(position)
.then((response) => {
return response;
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));
}
}
const getCoordinates = () => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
position => {
return resolve(position);
},
error => reject(error)
)}
);
};
// a call to my own API to make a request to Google's geocoding API
// response from this is coming back successfully
const getCityByCoords = (position) => {
const { latitude, longitude } = position.coords;
return axios.get('/city', {
params: {
lat: latitude,
lng: longitude
}
})
}
我的组件中的函数调用:
componentDidMount() {
this.getLocation();
}
getLocation() {
geolocate()
.then(
(response) => {
this.setState({
city: response,
isLoaded: true
})
},
(error) => {
this.setState({
isLoaded: true,
error
});
})
.then(() => {
this.setState({ isLoaded: 'false' });
})
}
我认为所有这些异步调用都让我失望。
【问题讨论】:
标签: javascript reactjs asynchronous promise async-await