在 async await 之后获取一组 Promises

Getting an array of Promises after async await

我正在尝试创建一个包含城市数组的每日预测映射数组。 我正在尝试映射城市数组,在页面加载后对每个城市进行 api 调用。 我不断收到一系列 Promises,例如:

最喜欢的页面组件:

  const [dailyForeCast, setDailyForeCast] = useState([]);

  const favorites = [
    {
      Key: '213181',
      type: 'City',
    },
    {
      Key: '213121',
      type: 'City',
    },
  ];


  useEffect(() => {
    const fetchData = async () => {
      const results = await favorites.map((city) => {
        return weatherService.getSingleForeCast(city.Key);
      });
      setDailyForeCast(results);
    };

    fetchData();
  }, []);
  console.log('dailyForest:', dailyForeCast);

通过 api 调用服务:

async function getSingleForeCast(value) {
  try {
    const res = await axios.get(`http://dataservice.accuweather.com/forecasts/v1/daily/1day/${value}`, {
      params: {
        apikey: API_KEY,
        details: true,
        metric: true,
      },
    });

    const result = res.data.DailyForecasts;

    return result;
  } catch {
    console.log('cant get single forecast');
  }
}

非常感谢任何帮助,提前致谢:)

正如 Brian 所说,您实际上并不是在等待 promises,而是在等待 map 函数。

尝试这样的事情(未经测试):

    const fetchData = async () => {
      const promises = favorites.map((city) => {
        return weatherService.getSingleForeCast(city.Key);
      });
      const results = await Promise.all(promises)
      setDailyForeCast(results);
    };