【问题标题】:React-Native Promise.all and Multiple API RequestsReact-Native Promise.all 和多个 API 请求
【发布时间】:2020-02-15 20:10:33
【问题描述】:

我正在尝试从 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
        });
      });
  };

【问题讨论】:

    标签: api react-native promise


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      Eric,很高兴您发现了错误! 或者,您可以使用 await 语法大大简化您的函数以提高可读性和清晰度。

        _getWeather = async(lat, long) => {
      
       let currentWeatherEndpoint = fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&APPID=${API_KEY}`);
       let dailyWeatherEndpoint = fetch(`http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${long}&APPID=${API_KEY}`);
      
       let finalVals = await Promise.all([currentWeatherEndpoint, dailyWeatherEndpoint])
      
          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
        });
      
      };
      
      

      【讨论】:

      • 感谢@cleme001。即使我发现了错误,你还是给了我一些额外的东西,我真的很感激。
      猜你喜欢
      • 2016-01-11
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2021-08-12
      • 2020-07-29
      相关资源
      最近更新 更多