JavaScript 获取 API 模板字符串

问题描述 投票:0回答:1

我正在尝试制作一个应用程序,根据您所在的位置提供天气信息。我通过 ipinfo 获取位置,并且有效。我将位置放入变量中,当我控制台记录它时,它仍然有效。但是,当我尝试使用模板字符串使用该变量从 openweathermap 获取数据时,控制台显示的是:

未捕获(承诺中)ReferenceError:当前城市未定义
在获取天气

问题是当我将该链接复制到控制台时,它会返回一个有效的链接!

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)
})
javascript fetch-api openweathermap
1个回答
0
投票

有两个异步调用,一个是getLocation(),另一个是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')
  }
}


const getWeather = async(currentCity) => {
  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")
  }
}



getLocation().then((city) => {
  currentCity = city;
  document.write(currentCity);
  return city;
}).then((city) => {
  return getWeather(city);
}).then((data) => {
  console.log(data)
}).catch((err) => {
  // Do something with it later
})

通过将以下承诺链接起来就可以实现。还修改了 getWeather() 方法以接受位置作为参数,使其成为可重用的单元。

getLocation().then((city) => {
  currentCity = city;
  document.write(currentCity);
  return city;
}).then((city) => {
  return getWeather(city);
}).then((data) => {
  console.log(data)
}).catch((err) => {
  // Do something with it later
})
© www.soinside.com 2019 - 2024. All rights reserved.