E
E
Evgeny Zhurov2020-02-26 14:33:41
JavaScript
Evgeny Zhurov, 2020-02-26 14:33:41

How to do a recursive sequential async-await?

It is necessary to strictly sequentially execute a series of asynchronous requests and push the received data into an array. The initial data has a tree structure:

let data = [{
  url: '/some-url',
  children: [
    {
      url: 'some-url',
      children: null
    },
    {
      url: 'some-url',
      children: [
        url: 'some-url',
        children: null
      ]
    }
  ]
},
{
  url: 'some-url',
  children: null
}]


It is required to write a loop that recursively processes the array, making requests for urls. Those. at the first iteration, it makes a request, waits for a response, pushes the response into an array, then checks if the object has children at this level, if it does, then it does the same with children. In other words, the output should be a one-dimensional array with data obtained from URLs. I'm using axios in a vue app, i.e. requests are made by this.axios.get(url).
What is the best way to solve such a problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-02-26
@Zhuroff

Consistently:

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

  if (Array.isArray(arr)) {
    for (const n of arr) {
      try {
        result.push({ status: true, result: await fetch(n.url).then(r => r.json()) });
      } catch(error) {
        result.push({ status: false, error });
      }

      result.push(...await fetchRecursive(n.children));
    }
  }

  return result;
}

Parallel:
const flat = arr => (arr || []).flatMap(n => [ n.url, ...flat(n.children) ]);

const fetchRecursive = arr => Promise.allSettled(flat(arr).map(n => fetch(n).then(r => r.json())));

A
Andrew, 2020-02-26
@AndrewRusinas

Habré solution

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question