Skip to content

Add WaitAny to make WaitAll return results incrementally

pranjal5215 edited this page Aug 15, 2012 · 6 revisions

Add WaitAny to make WaitAll return results incrementally

tornado.gen.task comprises of tornado.gen.CallBack and tornado.gen.Wait. Multiple CallBack-Wait pairs can be created distinguished by keys. WaitAll is provided by standerd tornado interface which returns results when all are finished processing. WaitAny subclasses WaitAll and returns responses made through AsyncHttpClient incrementally. See the commit at https://github.com/pranjal5215/tornado/commit/dd6902147ab2c5cbf2b9c7ee9a35b4f89b40790e

Sample usage:

class GenAsyncHandler2(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        http_client = AsyncHTTPClient()
        http_client.fetch("http://google.com",
                          callback=(yield tornado.gen.Callback("google")))

        http_client.fetch("http://python.org",
                          callback=(yield tornado.gen.Callback("python")))

        http_client.fetch("http://tornadoweb.org",
                          callback=(yield tornado.gen.Callback("tornado")))
        keys = set(["google", "tornado", "python"])
        while keys:
            key, response = yield tornado.gen.WaitAny(keys)
            keys.remove(key)
            # do something with response
            self.write(str(key)+"        ")
            self.flush()
        self.finish()