How does 'yield' work in tornado when making an asynchronous call?

夙愿已清 提交于 2019-12-05 10:07:27

You are already understanding how Tornado uses generators to handle async calls.

I'm assuming here that client is an instance of tornado.httpclient.AsyncHTTPClient(); it's fetch() method takes a callback function.

The tornado.gen.Task object only takes a reference to the client.fetch method; you are not calling it at that point. You are constructing a Task() instance with that method reference and an argument, then yielding that.

Tornado will then run that Task; the Task will in turn call client.fetch() with the argument provided, plus a callback function. The client.fetch() then runs asynchronously, and calls the callback. Whatever is then passed to the callback is then recorded as the Task result.

That result is then sent to your IndexHandler.get() generator with send(), returned from the yield Task() expression and assigned to response.

In other words, Tornado does use .send() here and something is assigned to response.

It sort of means "I give up control to you; come back when you have the result of this Future", and is thus kind of like an asynchronous dereferencing operator. Tornado responds by sending back the result when it's ready.

See http://tornado.readthedocs.org/en/latest/gen.html for a more in-depth explanation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!