【发布时间】:2020-12-25 03:15:17
【问题描述】:
我在通过天气 API 的异步获取函数传递用户位置时遇到问题。
代码
let lat = "48.8566";
let long = "2.3522";
const fetchWeatherData = (async (lat, long) => {
const response = await fetch(
" http://api.weatherstack.com/current?access_key={API_KEY}query=" + lat + "," + long
).then(resp => resp.json()).then(
function(apiResponse) {
console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
}
);
return await console.log(response.json());
})();
function setUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition);
console.log("click on button worked");
} else {
alert("location api not supported by browser");
}
}
function setPosition(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
fetchWeatherData.response(lat, long);
console.log("Lat: " + lat + " and Long:" + long);
}
我已尝试更改函数fetchWeatherData.response(lat, long);,但仍然无法绕过错误fetchWeatherData.response() is not a function at setPosition。我不确定我的错误是来自函数调用还是来自其他地方,例如async (lat, long) => ...。
我能够获取用户位置,但是当我尝试在异步函数中传递新的 lat 和 long 作为参数时,我的问题就开始了。
有没有更好的方法来解决这个问题?
【问题讨论】:
标签: javascript api asynchronous