Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda