Async function isn't behaving as intended in Django websocket consumer
I'm having some trouble with my django consumer for a game I'm making. The problem arises specifically when calling handle_timer in handle_round() from the loop in start_game(), update_timer isn't called until after the loop finishes. Why? Can you help me understand why this delay is occurring?
async def start_game(self):
#self.words = await bot.get_words(self.room.category, self.room.rounds)
self.words = ['worxd' for round in range(self.room.rounds)]
#self.words = json.loads(self.words)
print(self.words)
i = 1
for word in self.words:
print('Iteration', i)
await self.handle_round(word)
i += 1
async def handle_round(self, word_to_guess):
# Mark the current active round as inactive
if self.current_round:
self.current_round.is_active = False
await database_sync_to_async(self.current_round.save)()
# Create a new round
await database_sync_to_async(Round.objects.create)(
word=word_to_guess,
time_left=self.room.guess_time,
room=self.room,
)
self.current_round = await self.get_current_round()
print('Current round', self.current_round)
await self.update_game_state()
await self.handle_timer()
# Handle timer
async def handle_timer(self):
print('handle_timer')
if self.room and self.player and self.current_round:
# Broadcast the initial timer value to the room
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'update_timer',
'time': self.current_round.time_left,
}
)
async def update_timer(self,event):
print('update_timer')
asyncio.ensure_future(self.update_timer_helper(event))
Terminal output:
Iteration 1
Current round Round in <coroutine object Round.get_room at 0x0000018905541000>
handle_timer
Iteration 2
Current round Round in <coroutine object Round.get_room at 0x0000018905117E60>
handle_timer
update_timer
update_timer