简体   繁体   中英

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. 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. 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. 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...

      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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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