1

I have used async function inside the for loop, but the result is still not as expected, please check it for me. Here is my code:

      var labelCategory = await Label.find({is_deleted: false, datasetId: id}); //Array of labels with the same datasetId

      var arrayLabel = [];

      for await (const label of labelCategory) {
        
        var labelId = label._id;

        var dataLabel = {
          "labelId": "",
          "labelName": "",
          "totalImage": ""
        }

        await Image.countDocuments({ "labels.labelId": labelId, "datasetId": id }, function (err, count) {

          dataLabel["labelId"] = labelId;
          dataLabel["labelName"] = label.labelName;
          dataLabel["totalImage"] = count;
        
          arrayLabel.push(dataLabel);
        });
      }

      console.log(arrayLabel);
      res.send({"dataLabel": arrayLabel })

Every time I run this code, I get different results. Since I have all 68 images (22 dogs, 24 cats, 24 pandas) with the same datasetId, the result is what I expected as follows:

{
    "dataLabel": [
        {
            "labelId": "6234363e406b5e0bd4f9bb14",
            "labelName": "dogs",
            "totalImage": 22
        },
        {
            "labelId": "6234364c406b5e0bd4f9bb1b",
            "labelName": "cats",
            "totalImage": 24
        },
        {
            "labelId": "62343660406b5e0bd4f9bb23",
            "labelName": "pandas",
            "totalImage": 24
        }
    ]
}

But I don't know if I called the async function inside the loop correctly, so sometimes I run this code and it produces the following output:

{
    "dataLabel": [
        {
            "labelId": "6234364c406b5e0bd4f9bb1b",
            "labelName": "cats",
            "totalImage": 24
        },
        {
            "labelId": "6234364c406b5e0bd4f9bb1b",
            "labelName": "cats",
            "totalImage": 24
        },
        {
            "labelId": "62343660406b5e0bd4f9bb23",
            "labelName": "pandas",
            "totalImage": 24
        }
    ]
}

Please take a look. Thanks you so much

9
  • for await? Never seen that before. Is labelCategory an array? Why not foreach? Commented Mar 28, 2022 at 15:18
  • @zipzit: Maybe something like this? stackoverflow.com/questions/68172827/… Commented Mar 28, 2022 at 15:22
  • Oops. Right you are. for…of loop. Thx. Commented Mar 28, 2022 at 15:27
  • Please check where am I wrong? Thanks Commented Mar 28, 2022 at 15:30
  • When you ‘console.log(labelCategory)’ are the results as expected? Also if you remove await after for does that work better? You only need await callout for server requests Commented Mar 28, 2022 at 15:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.