I encountered two scenarios while trying to understand what was happening, but the clarity eluded me. I came across information suggesting that when running async calls in a for loop or map, Promise.all must be used. Let me share my experiences:
Initially, I utilized map to update multiple records in my database. It successfully updated some data but not all.
AllAuthToken.map(async singleToken => {
let deviceIds = uuidv4();
let newDeviceArray = {
[deviceIds]: singleToken.deviceToken,
};
await AuthToken.updateOne(
{ _id: singleToken._id },
{
$set: {
tokensDeviceArray: [newDeviceArray],
deviceId: [deviceIds],
},
},
{ $new: true }
);
}
Subsequently, I chose to use a for loop which effectively updated all the data:
for (let i = 0; i < AllAuthToken.length; i++) {
let deviceIds = uuidv4();
let newDeviceArray = {
[deviceIds]: AllAuthToken[i].deviceToken,
};
await AuthToken.updateOne(
{ _id: AllAuthToken[i]._id },
{
$set: {
tokensDeviceArray: [newDeviceArray],
deviceId: [deviceIds],
},
},
{ $new: true }
);
}
This discrepancy between the outcomes left me wondering why the first case failed while the second one succeeded.