Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda