Search code examples
asynchronoustornadoasynccallback

Tornado call callback function without waiting result


I have a server code using Tornado:

class mHandle(tornado.web.RequestHandler):

     @gen.coroutine
     def process(self, data):
         yield gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time() + 3)


     @tornado.web.asynchronous
     @gen.coroutine
     def get(self):
         _data = self.get_argument('data', default='')
         yield gen.Task(self.process, _data)
         self.write("OK")

And now, I using browser to enter localhost, it will wait 3s and then print the result "OK". I don't care about result, how to code to browser print "OK" immediately without having to wait 3s?

Thanks!


Solution

  • (going off of memory here)

    self.process returns a Future, so you could do something simple like:

     @tornado.web.asynchronous
     @gen.coroutine
     def get(self):
         _data = self.get_argument('data', default='')
    
        ioloop.add_future(self.process(_data), self.process_complete)
        self.write("OK")
    
     def process_complete(self, future):
        """Handle the error/success from the future"""
    

    You should probably do a self.finish("OK") since that will close the async.