B
B
bondle2021-10-03 22:45:52
Python
bondle, 2021-10-03 22:45:52

When is it necessary to use await when calling an async function?

Friends, tell me when you need to call await when working with asynchronous functions?
The situation is this: when working with either one that has asynchronous functions, let it be this . I can call a function from a non-async function. With this example

import time

async def work(p):
    time.sleep(2)

def endpoint():
    p = ""
    work(p)

endpoint()

It throws a never awaited error, which is logical.

I don't understand why the async function from lib works fine without await

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-10-04
@Vindicar

A distinction must be made between calling an asynchronous function and executing it.
In your case, the work(p) call will complete immediately (without entering the function body), and return a Future object.
This object describes the asynchronous operation to be performed (I/O, function execution, etc.).
You then schedule that object to run within a reactor loop (loop in asyncio terms).
To do this, you can use two methods. If you are in synchronous code, you should use loop.create_task() (or the older function, loop.ensure_future()).
If you are in asynchronous code, then your current function is already wrapped in its own Future, and is already executing within the reactor loop. Then you can use await to "give way" to the called function - schedule it to run in the same cycle as the calling function, and suspend the calling function until the called function finishes executing. Or, if you do not need to wait for the result of the called function, you can also use the first method.
So when you "call an async function with await" you are actually getting the future object and scheduling it right away.
Those. will be the same as
X = await foo()

future_X = foo()
#future_X можно хранить, но если он будет удалён без выполнения - это даст ошибку never awaited
X = await future_X

S
Samad_Samadovic, 2021-10-04
@Samad_Samadovic

import time

async def work(p):
    time.sleep(2)

def endpoint():
    p = ""
    await work(p)

endpoint()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question