user1187968
user1187968

Reputation: 8006

What will happen if you don't await a async function?

If I don't use await to call the async function, I will get back a coroutine. In that case, what will happen for the coroutine? Do I have to manually execute the coroutine? Or this coroutine will continue to run itself in the background?

Using await

async def work():
    result = await stuff()

Without await

async def work():
     result = stuff()

Upvotes: 10

Views: 7915

Answers (2)

Jorge Tovar
Jorge Tovar

Reputation: 1869

In Python it would ignore the call and print out the issue.

Different from the expected if you have a JavaScript background where the code is executed even if there is not an await.

import asyncio


async def main():
    print('Hello ...')
    asyncio.sleep(1)
    print('... World!')


asyncio.run(main())

Ignored

Hello ...
 World!
/Users/jtovar/PycharmProjects/stackoverflow/async_question.py:6: RuntimeWarning: coroutine 'sleep' was never awaited
  asyncio.sleep(1)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
import asyncio


async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')


asyncio.run(main())

it works!

Hello ...
 World!

it works! without await

async function sleep() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 1000);
  });
}

function main() {
  console.log('Hello ...');
  sleep();
  console.log('... World!');
}

main();

Hello ...
 World!

Upvotes: 1

kareem_emad
kareem_emad

Reputation: 1183

From the official docs:

Note that simply calling a coroutine will not schedule it to be executed:

That means you did not call your function actually so there no one waiting for anything and nothing to be waiting for if you did not place await before your function call.

You could instead schedule a task for it or many tasks using asyncio:

import asyncio

async def main():
    loop = asyncio.get_event_loop()
    t1 = loop.create_task(stuff())
    t2 = loop.create_task(stuff())

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

To find more about this, I would recommend reading https://docs.python.org/3/library/asyncio-task.html

Upvotes: 8

Related Questions