A
A
Alexey2020-06-30 14:03:53
JavaScript
Alexey, 2020-06-30 14:03:53

How to call fetch on each item when recursively iterating over tree objects and get a modified array as an output?

There is an array

const data = [
  {
    id: 1122029,
    children: [
      {
        id: 1122028,
        children: [
          {
            id: 1122027,
            children: []
          },
          {
           id: 1122022,
            children: []
          },
          {
            id: 1122022,
            children: []
          },
        ]
      }
    ]
  }
];

There is a fetch function that pulls by id and returns some data.
const fetchOptions (id) => {
  return fetch(`url${id}`).then(result => {
/* тут создаю объект на основе result и возвращаю его*/
    return data
  })
}


I iterate over the array like this:
const addingOptions = (array) => {
  array.forEach(item => {
    fetchOptions(item.id);
    
    if (item.children.length) {
      addingOptions(item.children)
    }
  })
}

At the output, I want to get an array with objects with additional fields that are added to the fetchOptions function.
And to throw this array further.
It seems that you need to use Promise here, but I can't figure out how to do it correctly.
How to wait for all asynchronous requests to complete and return the modified array?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-30
@Psihoshit

async function addOptions(arr) {
  const result = [];

  for (const item of arr) {
    result.push({
      ...item,
      options: await fetchOptions(item.id),
      children: await addOptions(item.children),
    });
  }

  return result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question