How to get the someone task's return immediately not until all task completed in [asyncio] ?
import asyncio
import time
print(f"now: {time.strftime('%X')}")
async def test1():
print(f"test1 started at {time.strftime('%X')}")
await asyncio.sleep(5)
with open('test.txt', 'w') as f:
f.write('...')
return 'end....'
async def test2(num):
print(f"test2 started at {time.strftime('%X')}")
return num * num
async def main(num):
res = await asyncio.gather(test1(), test2(num))
return res
def my(num):
return asyncio.run(main(num))[1]
print(my(5))
print(f"all end at {time.strftime('%X')}")
From the above code(python 3.7+), I can only get test2 return after test1 and test2 are all completed.
How can I let the main function get test2 return after test2 is completed, instead of waiting until test1 is completed?, because test2 is executed more quickly. And test1 must be executed(generate test.txt file.)
Than means return (test2's return) to main function or my function as soon as possible when test1 and test2 is asynchronous.