Answer the question
In order to leave comments, you need to log in
What is the easiest way to make a promise with nested enumeration of promises?
Hello.
It is necessary to receive the main list of the data through fetch.
From it I also get a list of links, through their enumeration and fetch in a cycle I get additional data.
And the result is sent to state.
BUT as a result, the state is empty, somewhere the promise is lost.
What is the correct and easiest way to arrange such a chain of promises with a nested fetch enumeration and get the result guaranteed to be saved in the state?
I currently have the following non-working code:
function dataPage() {
let fetchObject; // Главный контейнер, в конце его запишем в state
fetch('example.com') // Главный сайт
.then(response => response.json())
.then(data => {
fetchObject = data; // Сохраняем главный результат
fetchObject.arr = []; // Создаем массив, чтобы сюда сохранить список
data.URLs.map(url => { // Перебираем список URL из главного результата
fetch(url) // Запрашиваем данные с каждого url
.then(response => response.json())
.then(data => {
fetchObject.arr.push(data) // Сохраняем доп.данные
})
})
})
.then(() => {
// Сохраняем все результаты в state
setState(prevState => {
return (
{
...prevState,
fetchObject
}
)
})
})
}
Answer the question
In order to leave comments, you need to log in
Here, in order not to get confused and puzzle over endless callbacks, we introduced asynchronous functions.
There will be no comments on the code, everything is obvious here and does not need comments.
async function loadData() {
const response = await fetch("example.com");
const data = await response.json();
const links = await Promise.all(data.URLs.map(async (url) => {
const urlResponse = await fetch("example.com");
return await urlResponse.json();
}));
setState((prevState) => ({
...prevState,
fetchObject: {
...data,
URLs: links,
},
}));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question