首页 > 解决方案 > 如何将两个 fetch 请求合并到同一个数组中?

问题描述

我试图在一次调用中组合两个获取请求,以便我可以在同一个数组中获取所有数据。

我已经尝试过 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,

有更好的方法吗?

标签: javascriptreactjs

解决方案


我会做:

  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:通过数组解构可以轻松取回promise结果。

3:通过awaiting 你从async函数中获得实际好处:你不需要嵌套.then


推荐阅读