Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda