0

I'm trying to update a particular field in a user row, and I'm using a forEach loop to do this, but it's only the last loop to run that gets updated. here's how my code looks:

const UserSchema = require('../models/UserSchema');

const updates = [100, 200];
const userID = req.user.id;

updates.forEach(update => {
    UserSchema.findByID(userID).then(user => {
        user.balance += update;
        user.save.then(user => console.log('user balance updated'));
    })
})

After running this code, the user's balance should be '300', but instead it's '200'..it's like the last one to run overwrites the first one because they're running at very close intervals, i can;t just wrap my head around this...please what's the solution?

Nengak dakup
  • 88
  • 2
  • 11
  • This is just a quick example of the code, keep that in mind... I know you might give suggestions like find the User first and then loop through the updates, but my code won't permit that as it's a bit more complex... – Nengak dakup Aug 20 '20 at 21:55
  • Does this answer your question? [Resolve promises one after another (i.e. in sequence)?](https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence) – Matt Aug 20 '20 at 22:37

1 Answers1

1

You are dealing with an async loop here, but the code doesn't wait for the promises to complete before moving onto the next.

It's much easier using an async function.

async function updateBalances(userID, updates){
    for (const update of updates) {
      const user = await UserSchema.findByID(userID)
      user.balance += update
      await user.save()
    }
    console.log('user balances updated')
}
Matt
  • 68,711
  • 7
  • 155
  • 158