0

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);
    }
});
Daniel Corona
  • 839
  • 14
  • 34
  • None of the structure there looks problematic. Have you checked to see if the loop is iterating at all? (sounds like it isn't) If it is iterating, there's no way the `items` array contains no items at the end – CertainPerformance Jan 20 '22 at 02:04
  • 1
    `boxes.forEach(async box => {` is the problem - like you said in the question, `forEach` with promises inside won't work – CertainPerformance Jan 20 '22 at 02:09
  • @CertainPerformance I just checked it, and it seems like the loop gets executed before the ```console.log("Items", items);``` (check the changes I made to the question) – Daniel Corona Jan 20 '22 at 02:10
  • If the loop executes, the `items` array will most definitely have items in it at the end. Check `items.length`. – CertainPerformance Jan 20 '22 at 02:12
  • @CertainPerformance You were right, the culprit was the ```boxes.forEach``` loop, thank you! – Daniel Corona Jan 20 '22 at 02:17

0 Answers0