【问题标题】:Correct way to fetch data from an array of IDs?从 ID 数组中获取数据的正确方法?
【发布时间】:2021-01-28 23:23:42
【问题描述】:

目前我正在尝试使用 ID 列表来获取与 ID 一起出现的其余数据。我的代码如下:

export const fetchAllRoomData = createAsyncThunk(
  "socket/fetchAllRoomData",
  async ({ nspData }, thunkApi) => {
    if (!nspData) {
      return;
    }
    let fetchingRoomsData = [];
    nspData.roomIDs.forEach(async (r) => {
      const response = await getChatRoomData(r);
      console.log(response) -> THE RESPONSE IS HERE AND IS CORRECT
      fetchingRoomsData.push(response);
    });
    console.log(fetchingRoomsData); ----> THIS IS AN EMPTY ARRAY
    nspData.roomsData = fetchingRoomsData;
    return nspData;
  }
);

我已经尝试了很多不同的变体,但我似乎无法将传入的响应推送到新数组中。这样做的正确方法是什么。

【问题讨论】:

    标签: javascript reactjs react-native redux


    【解决方案1】:

    实际上,您正在将数据推送到数组中。问题是你没有等待它发生。您正在将一个异步函数传递给 forEach 调用。 forEach 是通过数组映射并为每个元素触发异步函数,但它不会等待每个函数完成。因此,当您将数组记录到控制台时,还没有完成任何异步调用。

    您可以做的(这只是几个可能选项的一种解决方案)是将您传递给 forEach 的函数变成一个同步函数,该函数将一个 Promise 推送到数组中,就像这样......

          nspData.roomIDs.forEach(r => {
    const fetchData = new Promise(resolve => {
        getChatRoomData(r)
        .then(response => {
            resolve(response)
        }
    fetchingRoomsData.push(fetchData);
    });
    

    然后等待数组中的promise解决,像这样...

    nspData.roomsData = await Promise.all(fetchingRoomsData)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-18
      • 2015-03-02
      • 2015-04-09
      • 2020-01-09
      • 2016-03-18
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      相关资源
      最近更新 更多