Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference of calling a normal function from async function with await a coroutine from an async function?

  1. async def caller():
        await bar()
        print("finish")
    
    async def bar():
       // some code here
    
  2. async def caller():
        bar()
        print("finish")
    
    def bar():
       //some code here
    

In above example. caller has to wait for the completion of bar() for both cases. Any difference for bar to be a normal / coroutine for this situation? If we want to "await" some functions, why not just use a normal function.

like image 494
shakalaka Avatar asked Aug 12 '20 07:08

shakalaka


People also ask

What is async await How is it different from coroutines?

The main difference between them is that while Async/await has a specified return value, Coroutines leans more towards updating existing data.

Can I use async await for normal function?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.

What is the purpose of async and await?

The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains. Async functions may also be defined as expressions.


1 Answers

The difference is that in the second example bar() is a non-async function, so it itself cannot await anything. For example, if you wanted to access a web service from within bar(), it wouldn't be a problem in the first example, you'd just use aiohttp. In the second example it would be pretty much impossible, as async libraries require being used from async functions, and non-async libraries will block the whole event loop while waiting for response.

If we want to "await" some functions, why not just use a normal function.

If the function you await doesn't need to communicate with the outside world (e.g. if it just shuffles data in a dict or so), it can and should be a normal function. On the other hand, if it needs to do IO, it should be an async function.

like image 175
user4815162342 Avatar answered Nov 15 '22 03:11

user4815162342