擅长:python、mysql、java
<p>在您的代码中,只需将waits添加到print语句中。事实上,这比那更容易:不要费心去创建一个任务;只需等待函数并直接打印值。此代码显示两种方法:</p>
<pre><code>import asyncio
import time
async def func_first(values):
await asyncio.sleep(2)
print('out: func_first')
return values
async def func_second():
s = asyncio.create_task(func_first(100))
await asyncio.sleep(3)
print('out: func_second', await s)
async def func_third():
print('out: func_third', await func_first(101))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
s = time.time()
loop.run_until_complete(func_second())
print('TIME:', time.time()-s)
loop.run_until_complete(func_third())
print('TIME:', time.time()-s)
</code></pre>
<p>结果:</p>
<pre><code>out: func_first
out: func_second 100
TIME: 3.062396764755249
out: func_first
out: func_third 101
TIME: 5.09357476234436
>>>
</code></pre>