【问题标题】:Promises in React appReact 应用程序中的 Promise
【发布时间】:2018-06-16 06:40:01
【问题描述】:

我已经坚持了几天了。我有一个使用天气 API 的反应应用程序。我做多个获取请求(通过循环)并得到承诺作为回报。我需要的是在承诺解决后结果(数组)设置状态。我认为我不应该链接.then,因为这样状态会根据数组的长度多次更改。

我负责 API 调用的函数是这样的:

apiRequest = (finalCitiesArray) => {
   let weatherArray =   finalCitiesArray.map((item) => {
  return (fetch("http://api.openweathermap.org/data/2.5/weather?id="+item.id+"&appid=API_KEY")
  .then(response => {
    return response.json();
  })
  .then(weather => {
   return weather;
  }))
})
this.setState({weather: weatherArray})}

我曾尝试使用 async/await,创建 new Promise,但我仍然无法使其正常工作。任何启示将不胜感激!谢谢。

【问题讨论】:

  • weatherArray 是一组在您调用 setState 时无法解决的承诺。您需要先使用Promise.all 等待它们全部解决(或拒绝)。

标签: javascript reactjs promise


【解决方案1】:

我建议您为此使用Promise.all。 使用它的代码是这样的:

apiRequest = async (finalCitiesArray) => {
    const weatherArrayPromises = finalCitiesArray
        .map(item => {
            return fetch("http://api.openweathermap.org/data/2.5/weather?id=" + item.id + "&appid=API_KEY")
                 .then(response => response.json());
         });

    const weatherArrayResults = await Promise.all(weatherArrayPromises); // <-- this is the line you're missing

    this.setState({ weather: weatherArrayResults });
}

请注意,我还删除了最后一个 then 子句,因为它并不是真正需要的。

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多