john_helt
john_helt•2mo ago

running async inside sync cells

I have a long chained function call, which needs to call some async function to fetch data from a database. I was thinking I could use asyncio to get the running loop, and then run the function inside that loop using "run_until_complete", but I just get an runtimeerror "this event loop is already running". How can I handle this without having to rewrite all my functions to async instead?
4 Replies
Myles Scolnick
Myles Scolnick•2mo ago
I am not sure what hackery this library does and if there is anything we can learn from it, but i was able to use nest_asyncio
import asyncio
import nest_asyncio
nest_asyncio.apply()

async def run_thing():
await asyncio.sleep(2)

asyncio.get_running_loop().run_until_complete(run_thing())
import asyncio
import nest_asyncio
nest_asyncio.apply()

async def run_thing():
await asyncio.sleep(2)

asyncio.get_running_loop().run_until_complete(run_thing())
john_helt
john_heltOP•2mo ago
Thanks, I did read about that, but it seems very hacky indeed 🙂 the function I need to call is inside a callback that is triggered when the user clicks a button. but I cant use async callbacks can I, so I have to make it sync ..
Myles Scolnick
Myles Scolnick•2mo ago
got it. yea we could maybe extend on_click to allow async. im not sure if there are any limitations for us to do that
Warmonger
Warmonger•2mo ago
This worked for me as well, though more straightforward behavior would be welcome 😉