javascript获取api模板字符串
我正在尝试制作一个应用程序,根据你的位置为你提供天气信息。我用ipinfo获得了位置信息,而且很有效。我将位置放在一个变量中,当我将其记录到控制台日志中时,它仍然有效。但是,当我尝试使用模板字符串从openweathermap获取带有该变量的数据时,控制台会显示:Uncaught(in promise)ReferenceError:currentCity未定义 在getWeather 问题是,当我将该链接复制到控制台时,它会返回一个有效的链接! 谢谢你的帮助javascript获取api模板字符串,api,fetch,Api,Fetch,我正在尝试制作一个应用程序,根据你的位置为你提供天气信息。我用ipinfo获得了位置信息,而且很有效。我将位置放在一个变量中,当我将其记录到控制台日志中时,它仍然有效。但是,当我尝试使用模板字符串从openweathermap获取带有该变量的数据时,控制台会显示:Uncaught(in promise)ReferenceError:currentCity未定义 在getWeather 问题是,当我将该链接复制到控制台时,它会返回一个有效的链接! 谢谢你的帮助 const getLocat
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)
})
有两个异步调用,一个是getLocation(),另一个是getWeather() 根据当前代码,它们都是异步运行的,没有定义任何序列流 您需要的是同步这两个位置,以便在获取该位置的天气之后获取第一个位置 下面是同步这两个方法以逐个执行的方法
const getLocation=async()=>{
const response=等待获取('http://ipinfo.io/json?token=(id由ipinfo提供)“)
如果(response.status==200){
const data=wait response.json()
返回数据。城市
}否则{
抛出新错误('无法获取当前位置')
}
}
const getWeather=async(currentCity)=>{
常数响应=等待
取回(`http://api.openweathermap.org/data/2.5/forecast?q=${currentCity}&units=metric&id=524901&APPID=(id由openweathermap给出)`);
如果(response.status==200){
const data=wait response.json()
返回数据
}否则{
抛出新错误(“无法获取天气”)
}
}
getLocation()。然后((城市)=>{
当前城市=城市;
文件。编写(当前城市);
回归城市;
}).然后((城市)=>{
回归天气(城市);
})。然后((数据)=>{
console.log(数据)
}).catch((错误)=>{
//以后再做点什么
})
您的代码需要同步流。我添加了一个相同的示例。看一看,如果这对你有效,请投票并接受答案,以便其他用户可以从中受益,如果没有,请给我留言。