Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
Nested fetch() array.map() cant return a value

My previous codes don't have a problem rendering HTML. I use just one fetch(). This time when it seems that I need to have two fetches, the first fetch will get just a product ID(coming from the user's cart) that I will use for the second fetch that will take the product details from the product collection.

Those IDs in the first fetch are in an array that's why I used map() to iterate through it while pulling up the product details for each product ID(through the 2nd fetch).

I thought this was going to work, but it seems I cannot get the return value for the map(), my innnerHTML doesn't output at all.

I'm fairly new to programming, if someone can help I would prefer an easy-to-understand method. Or just almost the same as my method I would prefer that or if you can just point out what I'm doing wrong or missing here with my code. Because as a beginner and based on my previous projects this logic is what I came up with, and I'd like to somehow make this work so as to be consistent at the moment.

    fetch(`${rootUrl}api/users/getCartItems`,{

    method: "GET",
    headers:{

        "Authorization": `Bearer ${token}`
    }
})
.then(result=>result.json())
.then(result=>{


    let cartItems = result.itemsArr.map(e=>{

        fetch(`${rootUrl}api/products/${e.item}`,{

            method: "GET"
    
        })
        .then(product=> product.json())
        .then(product =>{


        return `

            <br><br>
            ${e.item}<br>
            ${product.name}<br>
            ${product.description}<br>
            ${product.price}<br>
            <br><br>
        `

        })


    }).join(" ")

    content2 = document.querySelector('#content2');
    content2.innerHTML = cartItems;

})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your code is very hard to read. You might find it easier to understand promises using async/await than promise chaining with then, I have converted some of your code to use async await - but there is a little more work to do. Async await effectively creates synchronous blocking code, which is the kind of code you might be more used to.

As others have said, you cannot really use Javascript without a good knowledge of promises, so this is worth investing time in.

const getProducts = async () => {
  const results = await fetch(`${rootUrl}api/users/getCartItems`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  const resultsJSON = await results.json()

  const products = []
  let counter = 0
  while (counter < resultsJSON.itemsArr.length) {
    const fetchedProduct = await fetch(
      `${rootUrl}api/products/${resultsJSON.itemsArr[counter].item}`,
      {
        method: 'GET',
      },
    )
    const fetchedProductJSON = await fetchedProduct.json()
    products.push(fetchedProductJSON)
    counter++
  }
  // Do stuff with your products array
}
getProducts()
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda