在一行中执行两个GARCH时无法使React axios工作[重复]

9rnv2umw  于 5个月前  发布在  iOS
关注(0)|答案(3)|浏览(39)

此问题在此处已有答案

How do I return the response from an asynchronous call?(41个答案)
8天前关闭
我正在使用OpenWeatherMap来获取当前的天气,比如说,赫尔辛基。
我最新的MNWE(N作为non)是:

import axios from 'axios'

const apiKey = import.meta.env.VITE_OWM_API_KEY

const getCityCoordinatesApiUrl = (city) => {
    return `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
}

const getCityWeatherApiUrl = (longitude, latitude) => {
    return `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&appid=${apiKey}`
}

const getCityWeather = (city, weatherJsonContainer) => {
    const url = getCityCoordinatesApiUrl(city)
    let longitude = null
    let latitude = null

    axios.get(url).then(response => {
        console.log("Hell", response.data)
        longitude = response.data.coord.lon
        latitude = response.data.coord.lat
    })
    .catch(error => {
        console.log("Error in getCityWeather:", error)
        alert(`Could not obtain weather of ${city}!`)
    })

    console.log("getCityWeather: received:", latitude, longitude)

    const url2 = getCityWeatherApiUrl(longitude, latitude)

    const outData = axios.get(url2).then(response => response.data)
    
    console.log("getCityWeather: outData:", outData)
}

字符串
我的问题是longitudelatitude保持为null。我如何解决这个问题?我已经工作了几个小时了。

编辑1

在尝试code kindly provided by urchmaney之后,我的问题实现转换为以下内容:

import axios from 'axios'

const apiKey = import.meta.env.VITE_OWM_API_KEY

const getCityCoordinatesApiUrl = (city) => {
    return `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
}

const getCityWeatherApiUrl = (longitude, latitude) => {
    return `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&appid=${apiKey}`
}

const getCityWeather = (city) => {
    const url = getCityCoordinatesApiUrl(city)

    axios.get(url).then(response => {
        const longitude = response.data.coord.lon
        const latitude = response.data.coord.lat
        const url2 = getCityWeatherApiUrl(longitude, latitude)
        return axios.get(url2);
    })
    .then(response => {
        console.log(response.data)
        return response.data
    })
    .catch(error => {
        console.log("Error in getCityWeather:", error)
        alert(`Could not obtain weather of ${city}!`)
    })
}

export default {
    getCityWeather
}


(楼上打电话)

const weatherJsonData = weatherService.getCityWeather('Helsinki')


现在,我的问题是在第二个thenreturn response.data返回undefined

7xzttuei

7xzttuei1#

您需要等待第一个请求完成。将.catch()后面的代码放在.then()语句中

oxf4rvwz

oxf4rvwz2#

您需要链接API调用。您尝试访问经度和纬度的方式不在正确的上下文中。在返回API调用之前运行分配行console.log("getCityWeather: received:", latitude, longitude)
要链接API调用,您可以这样做

axios.get(url).then(response => {
        console.log("Hell", response.data)
        longitude = response.data.coord.lon
        latitude = response.data.coord.lat
        console.log("getCityWeather: received:", latitude, longitude)
        const url2 = getCityWeatherApiUrl(longitude, latitude)
        return axios.get(url2)
    })
     .then(res => {
      console.log("getCityWeather: outData:", res.data)
    })
    .catch(error => {
        console.log("Error in getCityWeather:", error)
        alert(`Could not obtain weather of ${city}!`)
    })

字符串
异步/等待实现

const getCityWeather = async(city) => {
   try {
      const response = await axios.get(url)
      const longitude = response.data.coord.lon
      const latitude = response.data.coord.lat
      const url2 = getCityWeatherApiUrl(longitude, latitude)
      return axios.get(url2)
   }
   catch (error) {
      console.log("Error in getCityWeather:", error)
      alert(`Could not obtain weather of ${city}!`)
   }
}


请记住,它是一个JavaScript方法,因此在使用它时需要等待它

const weatherJsonData = await weatherService.getCityWeather('Helsinki')

smtd7mpg

smtd7mpg3#

发送city,lat,lon,appid作为查询参数。我已经根据这个docs修改了API调用url。
试着使用promise-await来更好地处理promise。

const url = "https://api.openweathermap.org/data/2.5/weather"

const getCityWeather = async(city) => {
try {
  const response = await axios.get(url, {
    params: {
      q: city,
      appid: apiKey,
    },
  });
  console.log(response);
  const longitude = response.data.coord.lon;
  const latitude = response.data.coord.lat;
  const response2 = await axios.get(url, {
    params: {
      lat: latitude,
      lon: longitude,
      appid: apiKey,
    },
  });
  console.log(response2);
  return response2.data;
} catch (err) {
  alert(`Could not obtain weather of ${city}!`);
  console.log(err);
}

字符串
我已经删除了两个函数,因为URL是相同的,并使用axios参数发送数据。这将解决这个问题。
使用.then()和.catch():
代码中的更改:

axios.get(url).then(response => {
    const longitude = response.data.coord.lon
    const latitude = response.data.coord.lat
    const url2 = getCityWeatherApiUrl(longitude, latitude)

    // response need to be caught by .then() as a callback. It should not be returned.
    axios.get(url2).then(response => {
         console.log(response.data)
         return response.data
    }).catch((error) => {
         console.log("Error in getCityWeather:", error)
         alert(`Could not obtain weather of ${city}!`)
    })
})
.catch((error) => {
    console.log("Error in getCityWeather:", error)
    alert(`Could not obtain latitude and longitude of ${city}!`)
})


reactjsaxios

相关问题