[英]Puzzled about the coroutine of tornado
我試圖找出龍卷風的gen.py中流動的代碼。
future = TracebackFuture()
if replace_callback and 'callback' in kwargs:
callback = kwargs.pop('callback')
IOLoop.current().add_future(
future, lambda future: callback(future.result()))
try:
result = func(*args, **kwargs)
except (Return, StopIteration) as e:
result = getattr(e, 'value', None)
except Exception:
future.set_exc_info(sys.exc_info())
return future
else:
if isinstance(result, types.GeneratorType):
try:
orig_stack_contexts = stack_context._state.contexts
yielded = next(result) # A (mark)
if stack_context._state.contexts is not orig_stack_contexts:
yielded = TracebackFuture()
yielded.set_exception(
stack_context.StackContextInconsistentError(
'stack_context inconsistency (probably caused '
'by yield within a "with StackContext" block)'))
except (StopIteration, Return) as e:
future.set_result(getattr(e, 'value', None))
except Exception:
future.set_exc_info(sys.exc_info())
else:
Runner(result, future, yielded)
try:
return future
finally:
future = None
future.set_result(result) # B
return future
我有兩個功能。
@coroutine
def foo():
#do something
bar = yield bar()
#do something else
@coroutine
def bar():
#do something
return [1,2,3,4]
然后,調用foo()
函數,代碼運行到標記為A的點。將調用函數bar()
並且由於bar()
不是GeneratorType,它將像正常函數一樣運行。 接下來,設置未來結果並返回未來。 在返回未來之前設定結果的這一點最令人困惑。 在bar()
返回future之后, foo()
得到future,但是future在由io_loop.add_future
處理之前完成了set_result。
任何幫助將不勝感激,在此先感謝。
我是如此愚蠢的忽略代碼:
if self.handle_yield(first_yielded):
self.run()
如果將來完成,則該值將發送到相應的生成器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.