对此我感到很惊讶,因此想要一些有关我在使用异步Await语法时在哪里做错的指导。
“ getUserLocation”函数返回用户的位置:
getUserLocation = async () => {
const response = await window.navigator.geolocation.getCurrentPosition(
coord => ( coord.coords),
err => {
const { code, msg } = err;
if (code === 1) {
prompt(
"Location is needed to get the local salah time, please try again.",
msg
);
} else if (code === 2 || code === 3) {
prompt(
"Sorry, something went wrong, please try again or try again later.",
msg
);
}
},
{
enableHighAccuracy: true,
timeout: 5000,
}
);
// this.setState({
// userLocation: response,
// });
return response;
};
fetchTimes = async () => {
const { userLocation, method, month, year } = this.state;
const { lattitude, longitude } = userLocation;
if (!lattitude) {
let ress = await this.getUserLocation();
console.log("ress: ", ress);
const url = `http://api.address?latitude=${lattitude}&longitude=${longitude}&method=${method}&month=${month}&year=${year}`;
console.log("url:", url);
const resp = await fetch(url);
....
即使使用“ await”关键字调用了“ getUserLocation”,控制台仍会报告fetch
调用是在提示用户访问位置并将该位置返回到fetchTimes函数之前进行的。为什么在继续进行getUserLocation
调用之前不等待fetch
首先返回位置?
谢谢