0

I have a function as follows. All my GamePlayers are getting updated with the counter value of 1 - because the counter variable is updated after all update statements have completed.

Why is this like that and what can i do to make the counter increment each time a update query is done?

Future<bool> closeGame(List<GamePlayer> sortedWinnerList, Game game) async {
try {
  int counter = 1;
  await _database.transaction((txn) async {
    sortedWinnerList.forEach((element) async {
      print('xx update gamePlayer, counter= $counter');
      await txn.execute(
          'update $tableName_GAMEPLAYER set result_position = $counter where id=${element.id}');
      GameResult newResult = new GameResult(
          gameId: game.id,
          playerId: element.playerId,
          amount: element.gameWinAmount);
      await txn.insert(tableName_GAMERESULT, newResult.toJson());
      print('xx loop end, counter= $counter');
      counter++;
    });
    await txn.execute(
        'update $tableName_GAME set ended = ${DateTime.now().millisecondsSinceEpoch}');
  });

  return true;
} catch (e) {
  print('Game not closed: $e');
}

return false;

}

Helmut
  • 43
  • 4

1 Answers1

0

Edit: here's another relevant question: Async/await in List.forEach()

All the functions in forEach are spawned when counter was 1. They don't wait for each other.

If you want them to happen one after the other, you can do a regular loop and do an await in it.

Here's one step towards that goal. Might even just work.

Future<bool> closeGame(List<GamePlayer> sortedWinnerList, Game game) async {
try {
  int counter = 1;
  await _database.transaction((txn) async {
    for (final element in sortedWinnerList) {
      print('xx update gamePlayer, counter= $counter');
      await txn.execute(
          'update $tableName_GAMEPLAYER set result_position = $counter where id=${element.id}');
      GameResult newResult = new GameResult(
          gameId: game.id,
          playerId: element.playerId,
          amount: element.gameWinAmount);
      await txn.insert(tableName_GAMERESULT, newResult.toJson());
      print('xx loop end, counter= $counter');
      counter++;
    }
    await txn.execute(
        'update $tableName_GAME set ended = ${DateTime.now().millisecondsSinceEpoch}');
  });

  return true;
} catch (e) {
  print('Game not closed: $e');
}

return false;

Gazihan Alankus
  • 11,256
  • 7
  • 46
  • 57
  • It is exactly like explained in the answer, a simple for loop awaits the update query and increments the counter! – Helmut Nov 17 '20 at 13:45