0

I have a function that accepts a game found from a mongodb database via mongoose and the number of bots to add to the game object. the problem is after running the function only one bot object is being saved to the document even thought numOfBots is 3

async function addBot(game, numOfBots){

  for(index = 0; index < numOfBots; index++){
    let bot = {nickName: "Bot"}
    game.players.push(bot)
    game = await game.save()
  }
  return game
}

// elsewhere in another async function 
await addBot(game,3)

How can I use async await correctly in a regular for loop?

  • 3
    Why not save the `game` only once, after you put all the bots in its `.players` list? – Bergi Feb 09 '22 at 01:15
  • What does `game.save()` return? – Bergi Feb 09 '22 at 01:16
  • Your `index` variable is [accidentally global](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html). Don't forget to declare it, and always run your code in strict mode. Anything might be happening in that loop if you call the function (or other functions using the same `index`) multiple times concurrently. – Bergi Feb 09 '22 at 01:16
  • I don’t think this is an issue with async await. There is an issue with the mongoose setup. – OFRBG Feb 09 '22 at 01:17
  • declare the index value – aryankarim Feb 09 '22 at 01:18
  • you are right. After fixing that mistake of not declaring it as well as only saving it after the loop it added the document 3 times but I get a "Can't save() the same document multiple times in parallel error. Never mind it's an unrelated issue. Thank you – Personal Information Feb 09 '22 at 01:29
  • Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) –  Feb 10 '22 at 08:30
  • @AmirrezaFelfelian Not really, no. OP is not having trouble with `forEach` but with mongodb – Bergi Feb 10 '22 at 10:40

0 Answers0