juandisay
juandisay

Reputation: 1

Can't Call result on futures tornado , always result object

from somefolder import somelibrary

@gen.coroutine
def detailproduct(url):
    datafromlib=yield somelibrary(url)
    raise gen.Return(datafromlib)

expectation: See the result without request handler. not result like

{"data":<tornado.concurrent.future>}

I try like this link: "Can't call result() on futures in tornado" But not work.

Somebody help me! tx

Upvotes: 0

Views: 303

Answers (1)

xyres
xyres

Reputation: 21789

There are the two rules that you've to keep in mind while working with gen.coroutine:

  1. gen.coroutine decorated functions will automatically return a Future.
  2. If a function/coroutine is calling another coroutine decorated with gen.coroutine, it must also be decorated with gen.coroutine and must use the yield keyword to get its result.

detailproduct is decorated with gen.coroutine - which means it will always return the datafromlib wrapped in a Future.


How to fix

According to Rule 2, you've to decorate the caller with gen.coroutine and use the yield keyword to get the result of the Future.

@gen.coroutine
def my_func():
    data = yield detailproduct(url) 
    # do something with the data ...

OR

You can set a callback function on the Future that will be called when it gets resolved. But it makes the code messy.

def my_fun():
    data_future = detailproduct(url)
    data_future.add_done_callback(my_callback)

def my_callback(future):
    data = future.result()
    # do something with the data ...

Upvotes: 1

Related Questions