0
所以,我只是想换我周围的异步编程头(特别是龙卷风框架),我想我会从基础开始:调用“等待”两个协程:为什么两个连续的协程(异步函数)并行执行?
from tornado.ioloop import IOLoop
from tornado.web import Application, url, RequestHandler
from tornado.gen import sleep
class TestHandler(RequestHandler):
async def get(self):
f1 = await self.test("f1")
f2 = await self.test("f2")
self.write(f1 + " " + f2)
async def test(self, msg):
for i in range(5):
print(i)
await sleep(1) # this is tornado's async sleep
return msg
app = Application([url(r'/', TestHandler)], debug=True)
app.listen(8080)
ioloop = IOLoop.current()
ioloop.start()
的然而,问题是,当我在浏览器中点击localhost:8080
,并且在我的Python控制台盯着,我没有看到的0 1 2 3 4
2个交织序列,但两个连续的序列......
我读过的龙卷风FAQ一遍又一遍,似乎无法理解我做错了什么。
第二个代码块(期待已久)不能同时运行......我误解了你,它不应该被期望吗? – StevieP
啊,你说得对。这种模式使用'@ gen.coroutine'工作,但'async def'函数直到某些“等待”它们才开始。 –
你介意解释最佳实践吗?看起来Tornado和'asyncio'(特别是'async' /'await')并没有真正的配合。我们应该如何去编写/装饰异步代码(因为我们想要使用Tornado)? – StevieP