Suppose there is a library that makes various database queries:
import time
def queryFoo():
time.sleep(4)
return "foo"
def queryBar():
time.sleep(4)
return "bar"
I want to execute those 2 queries concurrently without having to add async
to the method signature or adding a decorator. These functions should not depend on asyncio at all.
What is the best way to utilize those non-async functions within asyncio
?
I am looking for something of the form:
#I need an 'asyncWrapper'
results = asyncio.gather(asyncWrapper(queryFoo()), asyncWrapper(queryBar()))
Thank you in advance for your consideration and response.
I presume you are after concurrency and hopefully do not insist on using
asyncio
module itself in which case this little example could be helpful:It runs both
queryFoo()
andqueryBar()
in parallel and collects their results in a list in order in which they've been mentioned in an assignment toresults
.If some function is blocking and not async by nature, only proper way to run it inside
asyncio
event loop is to run it inside thread using run_in_executor:It does job.
If you however want to avoid using threads only way to do it - is to rewrite
queryFoo
/queryBar
to be async by nature.