我试图在一次调用中合并两个获取请求,这样我就可以获取同一个数组中的所有数据。
我已经尝试过 Promise.all 方法,但我不知道它是否是正确的方法。
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:通过数组解构可以轻松取回promises结果。
3:通过 await
ing,您可以从 async
函数中获得实际好处:您不需要嵌套的 .then
链
关于javascript - 如何将两个获取请求合并到同一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55991302/