Rukinom
Rukinom

Reputation: 23

How to block on asyncio.Task call

I'm working with the Anki Cozmo SDK which requires use of async functions to actually make API calls. Trying to coordinate two of them which sometimes requires an optional "move" call prior to another async task.

Simply put I need two asynchronous tasks to run on the same loop, but not start the second until the first is finished.

loop = asyncio.get_event_loop()
async_tasks = []
async_tasks.append(asyncio.ensure_future(bot1.draw_line(), loop=loop))
async_tasks.append(asyncio.ensure_future(bot2.draw_line(), loop=loop))

if draw_util.point_conflicts(selected_plans, bot.position, CDIST):
    safe_position = draw_util.find_safe_point_2_robots(selected_plans, bot.position, CDIST + 1)
    task = asyncio.ensure_future(bot.move_to(safe_position), loop=loop)
    await task

await asyncio.gather(*async_tasks)

I need some way to wait for the move_to task to complete before continuing onto running the async_tasks. How could this be done?

I've tried using loop.run_until_complete() to the same effect.

Upvotes: 1

Views: 83

Answers (1)

Quanta
Quanta

Reputation: 622

I noticed this question after a whole year but here it is:

asyncio.wait_for function does exactly what you're (or actually you were) looking for. It blocks until a task is completed.

Please note that this function is a co-routine too, so you'll have to call it inside an async function.

Upvotes: 1

Related Questions