React app中的承诺

时间:2018-06-15 22:22:53

标签: javascript reactjs promise

我被困在这几天了。我有一个使用天气API的反应应用程序。我做多个get请求(通过循环)并得到承诺作为回报。我需要的是在解析promise后,结果(Array)设置状态。我想我不应该链.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,但我仍然无法使其正常工作。任何启示将不胜感激!感谢。

1 个答案:

答案 0 :(得分: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条款,因为它并非真正需要。