Answer the question
In order to leave comments, you need to log in
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()
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question