M
M
Mesuti2021-12-17 20:20:09
JavaScript
Mesuti, 2021-12-17 20:20:09

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

2 answer(s)
P
profesor08, 2021-12-17
@Mesuti

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,
    },
  }));
}

A
Alexandroppolus, 2021-12-17
@Alexandroppolus

Reading:
Promise.all
Promise.allSettled
async/
await

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question