首页 > 解决方案 > React-Native Promise.all 和多个 API 请求

问题描述

我正在尝试从 OpenWeather 中提取 2 个不同的 API 请求,用于使用 React-Native 编写的天气应用程序。无论如何,我是使用 API 的新手,但我也在尝试同时使用 2。我已经浏览了十几个教程,但无法使其正常工作。最讨厌的一个看起来很直接,但我不断收到 linting 错误。任何帮助,将不胜感激。这是最新的代码/尝试。我的 linter 一直说 ; 或者,在...之后

let currentWeather => finalVals[0];

let dailyWeather => finalVals[1];

...是错误的,但改变它们也无济于事。这是我也在使用的这个教程的链接:https ://medium.com/@gianpaul.r/fetching-from-multiple-api-endpoints-at-once-ffb1b54600f9

这是我的代码:

_getWeather = (lat, long) => {

     let currentWeather = fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&APPID=${API_KEY}`);
     let dailyWeather = fetch(`http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${long}&APPID=${API_KEY}`);

     Promise.all([currentWeather, dailyWeather])
      .then(values => Promise.all(values.map(value => value.json())))
      .then(finalVals => {
        let currentWeather => finalVals[0];
        let dailyWeather => finalVals[1];

        this.setState({
          temperature: Math.floor((currentWeather.main.temp) - 273.15),
          name: currentWeather.weather[0].main,
          location: currentWeather.name,
          isLoaded: true
        });
      });
  };

标签: apireact-nativepromise

解决方案


叹息......在我的头撞到墙上一个小时后,我意识到我在不应该有的地方有功能箭头。除非有人发现此方法有任何其他问题,否则对这篇文章表示最深切的歉意。


推荐阅读