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