Home > Back-end >  Error assigning correct value to my variables with forEach
Error assigning correct value to my variables with forEach

Time:10-08

I'm trying to iterate through some products and then assignate the summatory of the elements to an object.

This is my code, but it seems like the assignation is running first and then everything inside the forEach.

How could I wait until the forEach has finished in order to apply the correct value to my variables?

            const megaCheck = async (prods) => {   
        let puntosGastados  = 0   
        let stickersGastados = 0   
        const productos = prods[0].items   
        let host = ''   if (
                window.location.host.split('.')[0].indexOf('wongfoodqawlschv6io') > -1 ) {
                host = 'wongfoodqawlschv6io'   } else if (window.location.host.split('.')[0].indexOf('metroqaio') > -1) {
                host = 'metroqaio'   }   
        productos.forEach(async (producto, index) => {
                try {
                  const { data } = await axios.get(`/api/catalog_system/pub/products/search?fq=productId:${producto.id}`)
                  if(data[0]["mega-promo"].length){
                    let megaInfo = JSON.parse(data[0]["mega-promo"])
                    puntosGastados  = (megaInfo.puntos * producto.quantity)
                    stickersGastados  = (megaInfo.stickers * producto.quantity)
                    console.log("Puntos gastados --"   puntosGastados)
                    console.log("Stickers gastados --"   stickersGastados)
                  }
                 } catch (error) {
                  console.error(error)
                }   })   
console.log(puntosGastados)  
 console.log(stickersGastados)  
 setMegaUserInfo({
                points: puntosGastados,
                stickers: stickersGastados   }) 
      console.log(megaUserInfo) }

And my output is: OUTPUT

CodePudding user response:

I believe that you would be able to achieve what you want by using the useRef hook

puntosGastados = useRef(0)
stickersGastados = useRef(0)

...

puntosGastados.current  = (megaInfo.puntos * producto.quantity)
stickersGastados.current  = (megaInfo.stickers * producto.quantity)


https://reactjs.org/docs/hooks-reference.html#useref

CodePudding user response:

You can wait for every iteration to be completed using Promise.all

Promise.all() documentation

await Promise.all(
  // Replacing forEach with map because we need to get the promise of each iteration
  productos.map(async (producto, index) => {
    try {
      const { data } = await axios.get(
        `/api/catalog_system/pub/products/search?fq=productId:${producto.id}`
      );
      if (data[0]["mega-promo"].length) {
        let megaInfo = JSON.parse(data[0]["mega-promo"]);
        puntosGastados  = megaInfo.puntos * producto.quantity;
        stickersGastados  = megaInfo.stickers * producto.quantity;
        console.log("Puntos gastados --"   puntosGastados);
        console.log("Stickers gastados --"   stickersGastados);
      }
    } catch (error) {
      console.error(error);
    }
  })
);
console.log(puntosGastados);
console.log(stickersGastados); 
  • Related