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()
function sleep(n){
// ES6 does not provide native sleep method with promise support
return new Promise(res => setTimeout(res, n * 1000));
}
async function countdown(n){
while(n > 0){
console.log(n);
n -= 1;
await sleep(1);
}
}
async function main(){
// Creates two promises
var promises = Promise.all([
countdown(3),
countdown(2)
]);
// Wait for all of them to finish
await promises;
// Cannot stop interpreter's event loop
}
main();
需要注意的一点是,这些代码非常相似并且工作方式基本相同。
以下是问题:
在Python和ES6中,
await/async
都是基于生成器的。认为Futures与Promises相同是否正确?我在
asyncio
文档中看到了术语Task
、Future
和Coroutine
。它们之间有什么区别?我应该开始编写始终具有运行事件循环的Python代码吗?