此问题在此处已有答案:
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)
}
字符串
我的问题是longitude
和latitude
保持为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')
型
现在,我的问题是在第二个then
:return response.data
返回undefined
。
3条答案
按热度按时间7xzttuei1#
您需要等待第一个请求完成。将.catch()后面的代码放在.then()语句中
oxf4rvwz2#
您需要链接API调用。您尝试访问经度和纬度的方式不在正确的上下文中。在返回API调用之前运行分配行
console.log("getCityWeather: received:", latitude, longitude)
。要链接API调用,您可以这样做
字符串
异步/等待实现
型
请记住,它是一个JavaScript方法,因此在使用它时需要等待它
型
smtd7mpg3#
发送city,lat,lon,appid作为查询参数。我已经根据这个docs修改了API调用url。
试着使用promise-await来更好地处理promise。
字符串
我已经删除了两个函数,因为URL是相同的,并使用axios参数发送数据。这将解决这个问题。
使用.then()和.catch():
代码中的更改:
型
reactjsaxios