I need to do async/await
inside for..loop
, but that way I can't do parallel operations.
So I am pushing those promises into an variable promises
later I will do promise.all()
on it.
Here is my code.
const promises = [];
for (let i = 0; i < todayAssignedJobs.length; i += 1) {
promises.push(Leaderboard.findOrCreate({...}).then((leaderboard, created) => {
if (!created) {
const rating = (todayAssignedJobs[i].rating + leaderboard.rating * leaderboard.jobs_completed) / (leaderboard.jobs_completed + 1);
const commission = todayAssignedJobs[i].commission + leaderboard.commission;
const jobsCompleted = leaderboard.jobs_completed + 1;
Leaderboard.update({
rating,
commission,
jobs_completed: jobsCompleted,
updated_by: 'system',
}, {
where: {
id: leaderboard.id,
},
});
}
AssignedJob.update({
is_leaderboard_generated: true,
}, {
where: {
id: todayAssignedJobs[i].id,
},
});
}));
}
await Promise.all(promises)
Somehow, I am unable to get the id when I do Assigned.update({..}, { where: { id: todayAssignedJobs[i].id }})
Getting error:
Unhandled rejection Error: WHERE parameter "id" has invalid "undefined" value
Can someone explain what is going on? Also, please suggest can I do below?
promises.push(async () => { // I will use await here })