Search code examples
pythonasynchronousasync-awaittimeoutpython-asyncio

Returning immediate value and then call asyncio.sleep


I need help with this exercise please, I have this function:

async def check_name(self):
        await asyncio.sleep(5)
        if SOmeFunction():
            DoSomethng
        else:
            DosomethingElse

Now I want to call the above function in other function but the prblem is that I want the below function to return an immediate value and then call check_name(). This is what I've done so far ( I thought of adding try.. finally but it didnt't work it is calling check_name first then waits 5 seconds and then it is returning the actual value. I want to return the value first then call check_name()

async def func():
        value = func2()
        try:
          return value

        finally:
          await self.check_name()

Solution

  • You can use asyncio.create_task to instruct the event loop to await check_name itself, i.e. to run it in the background:

    async def func():
        asyncio.create_task(self.check_name())
        value = func2()
    

    Note that, if you do this, the return value of check_name() will not be available, and if it raises an exception, it will just be reported by the event loop.