0
votes

I'm not sure how to use aync/await. Assume I have this function:

async def test():
   result = get_db_data() # to get records from db
   return result

So, here get_data is not an asynchronous function, and wehn I call test() I use await test(). But my question is that code considered async or should I also make get_data and async func and call it with await?

Please I need help

Note: I have tried to add await asyncio.sleep(30) in test function and I tested 2 requests at the same time, so it seems that it is working beacuse it returned both results after 30 seconds (so it didn't take 60 seconds)

2

2 Answers

0
votes

Backgorund

Here is a little example that I hope will help you understand. Say here is your function

async def test():
    # does something

Now, why did we make it asynchronous? Say, we had to use it in another threaded method.

async def threaded_f():
            result = await test()
            # Some random code to get variable Y
            Y = Y + result

Now, the advantage of making test() async is, that at the line result = test() the thread will wait for the outcome of test() because it's return value is to be used later in code. If it were a function of the type void, we might not have awaited the call and let the threaded function keep its execution.

Answer

So, to answer your question. Yes, you may make get_db_data() async and await as it is the same kind of case as discussed in threaded_f function. The results are needed to be stored in a variable.

0
votes

In answer to your question, get_db_data will not be treated as asynchronous just because it is inside the async test coroutine.

You need to understand the event loop and coroutines to answer your question well.

If your synchronous routine does not block then you can get away with it, but you need to understand what it is doing thoroughly to ensure it does not cause unexpected delays. If you don't want your program to be blocked by get_db_data then you need to make it awaitable, eg a coroutine.

asyncio docs