Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

260
Views
How to call an async function inside for loop in JavaScript / node js?

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!