【问题标题】:javascript fetch api template stringjavascript 获取 api 模板字符串
【发布时间】: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 用户可以从中受益,如果没有,请给我留言。

标签: api fetch


【解决方案1】:

异步调用有两种,一种是getLocation(),一种是getWeather()

根据目前的代码,两者都是异步运行的,没有定义任何序列流。

您需要同步这两者,以便第一个位置天气之后获取该位置。 p>

以下是您可以同步两种方法以依次执行的方式。

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
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2016-10-28
    • 2021-04-01
    相关资源
    最近更新 更多