Answer the question
In order to leave comments, you need to log in
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
}]
Answer the question
In order to leave comments, you need to log in
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;
}
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())));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question