擅长:python、mysql、java
<p>是,<code>tornado</code>是异步的。您展示的示例是一个<a href="http://www.tornadoweb.org/en/stable/gen.html#tornado.gen.coroutine" rel="nofollow">^{<cd2>}</a>;它实际上是非阻塞的,并在<code>yield</code>调用时将控制释放回tornado事件循环。控件只在两个<code>http_client.fetch</code>调用实际完成时返回<code>get</code>函数。在</p>
<p>这两个例子实际上在<code>tornado</code>中功能等效:</p>
<pre><code>class AsyncHandler(RequestHandler):
@asynchronous
def get(self):
http_client = AsyncHTTPClient()
http_client.fetch("http://example.com",
callback=self.on_fetch)
def on_fetch(self, response):
do_something_with_response(response)
self.render("template.html")
</code></pre>
<p>还有一个协同程序版本:</p>
^{pr2}$
<p>协同程序允许您编写异步代码,它看起来是同步的,可读性更强。当上面的代码命中<code>yield</code>,<code>get</code>将挂起并将<code>http_client.fetch</code>返回给<code>gen.coroutine</code>装饰器的<a href="http://www.tornadoweb.org/en/stable/concurrent.html#tornado.concurrent.Future" rel="nofollow">^{<cd9>}</a>对象。<code>gen.coroutine</code>修饰符有魔力,它可以安排<code>fetch</code>调用返回的<code>Future</code>的结果,以便在准备就绪后将其传递回<code>get</code>。在</p>