I am newbie on async await approach. I built the function where async await approach is used. But somehow my sequence is break through forEach Loop
const newUser = async () => {
try {
let t1Data = await Users.find({ sequenceid: 1 });
if (t1Data.length > 0) {
let newData = t1Data[0].messagescore;
console.log("A");
newData.forEach(async (x, i) => {
let updateColumn = await Users.update(
{ sequenceid: 1 },
{
$push: {
messagescorebefore: {
userid: x.userid,
score: parseFloat(x.score.toFixed(2))
}
}
}
);
console.log(i + " Updated");
return updateColumn;
});
console.log("B");
}
} catch (e) {
console.log(e);
}
};
newUser();
By this console sequence will be like this
-> A
-> B
-> 0 Updated
-> 1 Updated
Now Desired result will be like this which I did not get:
-> A
-> 0 Updated
-> 1 Updated
-> B
May be I am doing something wrong on forEach Loop.
Guys if you know where I am wrong then please let me know. Any help is really Appreciated.
/********** Updated Logic as suggestion But still got one issue *************/
const newUser = async () => {
try {
let t1Data = await Users.find({ sequenceid: 1 });
if (t1Data.length > 0) {
let newData = t1Data[0].messagescore;
console.log("A");
await Promise.all(
newData.map( async (x, i) => {
let updateColumn = await Users.update(
{ sequenceid: 1 },
{
$push: {
messagescorebefore: {
userid: x.userid,
score: parseFloat(x.score.toFixed(2))
}
}
}
);
console.log(i + " Updated");
return updateColumn
})
)
console.log(i + " Updated");
return updateColumn;
});
console.log("B");
}
} catch (e) {
console.log(e);
}
};
newUser();
In this Logic Some Times my Loop breaks under map Function. Rest all things work fine.
Under map Function I console (i), so some times it breaks the sequence..
Can anyone guide me where I am wrong.....