从Python 3.5开始,关键字await和async语言都被引入.现在,我更像是一个Python 2.7人,而且我已经在相当长一段时间内避免使用Python 3了,所以asyncio对我来说这是一个新手.根据我的理解,它似乎await/async与它们在ES6(或JavaScript,ES2015中的工作方式)的工作方式非常相似,但是您想要称之为.
这是我用来比较它们的两个脚本.
import asyncio
async def countdown(n):
while n > 0:
print(n)
n -= 1
await asyncio.sleep(1)
async def main():
"""Main, executed in an event loop"""
# Creates two countdowns
futures = asyncio.gather(
countdown(3),
countdown(2)
)
# Wait for all of them to finish
await futures
# Exit the app
loop.stop()
loop = asyncio.get_event_loop()
asyncio.ensure_future(main())
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)
function sleep(n){
// ES6 does not provide native sleep method with promise support …Run Code Online (Sandbox Code Playgroud)