Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

82
Vistas
Async/await array does not get populated

I'm trying to fill an array, however, when I try to print it, the array always appears empty. I don't know if this could be because of the async function inside my loop:

static async getInventoryForBox(box, quantities) {
  const thisBoxInventory = box.toObject().inventory;
  const items = [];

  for (const object of thisBoxInventory) {
     const inventoryItem = await InventoryController.getInventoryItem(object);
     let updatedJSON = { };
     const cardID = inventoryItem.card;
     const quantitiesArray = inventoryItem.toObject().quantities;
     const quantityID = quantitiesArray[0];
     const quantityValue = quantities.find(object => object._id.$oid === quantityID.toString());

     updatedJSON = {
         card: { $oid: cardID },
         quantity: quantityValue.value,
         box: { $oid: box._id },
         list: null
     }
        
     items.push(updatedJSON);
  }

  console.log("ItemsA", items); // Prints []
  return items;
}

Previously, the loop was a forEach, however, I understood that that brings more problems than it solves, so I changed it for a for of loop, however, that doesn't seem to fix the issue

I'm calling the function from here:

router.get('/', TokenController.isAValidToken, async (req, res) => {
    const { setID } = req.query;
    try {
        if (setID != null) {
            const boxes = await BoxesController.getBoxesForSet(setID);
            res.json(boxes);
        } else {
            const boxes = await BoxesController.getAllBoxes();

            boxes.forEach(async box => {
                const quantities = await BoxesController.readFile();
                const items = await BoxesController.getInventoryForBox(box, quantities);
                console.log('Items', items);
            });
            res.json(boxes);
        }
    } catch (error) {
        ErrorController.errorCallback(error, res);
    }
});
7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos