简体   繁体   English

从 ID 数组中获取数据的正确方法?

[英]Correct way to fetch data from an array of IDs?

Currently I am trying to use a list of ID's to fetch the rest of the data that goes along with the ID.目前我正在尝试使用 ID 列表来获取与 ID 一起的数据的 rest。 My code reads as follows:我的代码如下:

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;
  }
);

I have tried so many different variations of this, but I cannot seem to be able to push the incoming response into a new array.我已经尝试了很多不同的变体,但我似乎无法将传入的响应推送到一个新数组中。 What is the correct way to do this.执行此操作的正确方法是什么。

Actually, you are pushing the data into the array.实际上,您是将数据推入数组。 The problem is that you are not waiting for it to happen.问题是你没有等待它发生。 You are passing an asynchronous function into the forEach call.您正在将异步 function 传递到 forEach 调用中。 The forEach is mapping through the array and firing off the asynchronous function for each element, but it doesn't wait for each function to finish. forEach 通过数组进行映射并为每个元素触发异步 function,但它不会等待每个 function 完成。 So when you log the array to the console, none of the asynchronous calls have completed yet.因此,当您将数组记录到控制台时,尚未完成任何异步调用。

What you could do (and this is only one solution of a few possible options) is make the function that you pass to forEach into a synchronous function that pushes a promise into the array, like this...你可以做的(这只是几个可能选项的一个解决方案)是将传递给 forEach 的 function 变成一个同步的 function ,将 promise 推入数组,就像这样......

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

Then wait for the promises in the array to resolve, like this...然后等待数组中的承诺解决,像这样......

nspData.roomsData = await Promise.all(fetchingRoomsData)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM