11

I have the following code:

import asyncio

async def test_1():      
    res1 = await foo1()
    return res1

async def test_2():      
    res2 = await foo2()
    return res2

if __name__ == '__main__':
    print(asyncio.get_event_loop().run_until_complete([test_1, test_2]))

But the last call to .run_until_complete() is not working. How can I perform an async call to multiple tasks using .run_until_complete()?

1 Answer 1

18

I was looking for examples and I found the answer. We can run a simple tasks, which gathers multiple coroutines:

import asyncio    

async def test_1(dummy):
  res1 = await foo1()
  return res1

async def test_2(dummy):
  res2 = await foo2()
  return res2

async def multiple_tasks(dummy):
  input_coroutines = [test_1(dummy), test_2(dummy)]
  res = await asyncio.gather(*input_coroutines, return_exceptions=True)
  return res

if __name__ == '__main__':
  loop = asyncio.get_event_loop()
  res1, res2 = loop.run_until_complete(multiple_tasks(dummy=0))
Sign up to request clarification or add additional context in comments.

2 Comments

This gives me RuntimeError: There is no current event loop in thread 'MainThread'.
@FrankieDrake Try adding: try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() instead of just asyncio.get_event_loop()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.