【发布时间】:2018-07-01 07:35:57
【问题描述】:
我正在尝试制作一个根据您的位置为您提供天气信息的应用。我通过 ipinfo 获得了位置,它可以工作。我将位置放在一个变量中,当我控制台记录它时它仍然有效。但是,当我尝试使用模板字符串从带有该变量的 openweathermap 获取数据时,控制台显示的是:Uncaught (in promise) ReferenceError: currentCity is not defined 在 getWeather 问题是当我将该链接复制到控制台时,它会返回一个有效的链接! 感谢您的帮助
const getLocation = async () => {
const response = await fetch('http://ipinfo.io/json?token=(id given by ipinfo)')
if (response.status === 200) {
const data = await response.json()
return data.city
} else {
throw new Error('Unable to get the current location')
}
}
let currentCity
getLocation().then((city) => {
currentCity = city
document.write(currentCity)
}).catch((err) => {
// Do something with it later
})
const getWeather = async () => {
const response = await
fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${currentCity}&units=metric&id=524901&APPID=(id given by openweathermap)`);
if (response.status === 200) {
const data = await response.json()
return data
} else {
throw new Error("Unable to get weather")
}
}
getWeather().then((data) => {
console.log(data)
})
【问题讨论】:
-
您的代码需要同步流程。我已经添加了一个相同的示例。看看它,如果这对你有用,请投票并接受答案,以便其他 SO 用户可以从中受益,如果没有,请给我留言。