我试图在一个呼叫中组合两个提取请求,以便我可以在同一数组中获取所有数据。
我已经尝试了所有方法,但我不知道这是否是正确的方法。
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
//const api_call = await
const promises = await Promise.all([
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&APPID=${API_KEY}`),
fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&APPID=${API_KEY}`)
])
const data = promises.then((results) =>
Promise.all(results.map(r => r.text())))
.then(console.log)
代码实际上有效,我正在获取数据,但我不了解JSON响应。
(2) ["{"coord":{"lon":-5.93,"lat":54.6},"weather":[{"id"…7086601},"id":2655984,"name":"Belfast","cod":200}", "{"cod":"200","message":0.0077,"cnt":40,"list":[{"d…on":-5.9301},"country":"GB","population":274770}}"]
我应该如何设置状态?我的状态是这样设定的,只有一个电话。
if (city) {
this.setState({
temperature: data[0].main.temp,
city: data[0].name,
有更好的方法吗?
我会做:
getWeather = async (e) => {
e.preventDefault();
const fetchText = url => fetch(url).then(r => r.json()); // 1
const /*2*/[weather, forecast] = /*3*/ await Promise.all([
fetchText(`.../weather`),
fetchText(`.../forecast`)
]);
this.setState({ temperature: weather.temp, /*...*/ });
}
1:通过使用小助手,您不必两次致电Promise.all
。因此,这两个请求都是并行完成的(您应该使用.json()
作为JSON分析(。
2:通过阵列破坏您可以轻松地获得承诺结果。
3:通过await
,您可以从async
函数中获得实际收益:您不需要嵌套.then
链
您可以按照以下方式编写,这是更清洁的方法,并且将您的数据分类
const success = res => res.ok ? res.json() : Promise.resolve({});
const weather = fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&APPID=${API_KEY}`)
.then(success);
const forecast = fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&APPID=${API_KEY}`)
.then(success);
return Promise.all([weather, forecast])
.then(([weatherData, forecastData]) => {
const weatherRes = weatherData;
const ForecastRes = forecastData; // you can combine it or use it separately
})
.catch(err => console.error(err));
}