Reputation: 39
I have two function kitchen()
and waiter()
. In waiter()
I have awaited kitchen()
function. I know that if I await the function it will be waiting until that particular function returns. Here, in waiter await kitchen()
means "Wait until the kitchen() function returns something"
. I have doubt that what is the use of this await with async compared to normal flow execution like below.
What is the difference between two programs?
Thanks in advance 😄.
I have try to understand the difference between these two programs. But no clue found.
Upvotes: 2
Views: 4587
Reputation: 6808
If you define an async function, say:
async def fun1():
return 10
when you call the function:
>>> fun1()
<coroutine object fun1 at xxxxx>
As you can see, it returns a "coroutine". This coroutine needs to be executed by an "async event loop".
await
is the keyword that means "execute this coroutine and give me its return value". But await
is only legal inside another async function.
So if you do:
>>>await fun1()
You'll get a SyntaxError
So we need to write another async function, and use an async framework to execute that function:
async def call_this():
print(fun1())
print(await fun1())
import asyncio
asyncio.run(call_this())
You'll get:
<coroutine object fun1 at ...>
10
... plus a warning that there's a coroutine object that was never "awaited".
As you can see, the first invocation of fun1()
without await
still returns a coroutine object. The await
keyword triggers the actual execution of the coroutine object, in this case the function fun1()
, and returns the function's return value.
So, what is the difference?
The difference is that async
allows "asynchronous" execution of tasks. It's not parallel processing; rather, at certain points where the task needs to wait on an external resource (e.g., waiting for download of a file to finish) it can 'yield' execution to other tasks.
"asynchronous", in other words, is "cooperative multitasking": Every task must explicitly yield at certain points to allow other tasks to run. The await
keyword is also a signal that at this point the task will have to wait a response from another coroutine, so the async event loop can 'switch' to doing other tasks.
Imagine asynchronous as a restaurant with a single waiter. Rather that getting a table's order, sending the order to the kitchen, and wait until the order is complete, the waiter just hands over the order to the kitchen and proceeds to take the order from other tables, while regularly checking the kitchen window for finished orders.
So rather than:
The waiter will do:
Upvotes: 6