【发布时间】:2015-01-05 22:51:41
【问题描述】:
部分实现inlineCallbacks是这样的:
if isinstance(result, Deferred):
# a deferred was yielded, get the result.
def gotResult(r):
if waiting[0]:
waiting[0] = False
waiting[1] = r
else:
_inlineCallbacks(r, g, deferred)
result.addBoth(gotResult)
if waiting[0]:
# Haven't called back yet, set flag so that we get reinvoked
# and return from the loop
waiting[0] = False
return deferred
result = waiting[1]
# Reset waiting to initial values for next loop. gotResult uses
# waiting, but this isn't a problem because gotResult is only
# executed once, and if it hasn't been executed yet, the return
# branch above would have been taken.
waiting[0] = True
waiting[1] = None
如图所示,如果在 inlineCallbacks-decorated 函数中,我会这样调用:
@inlineCallbacks
def myfunction(a, b):
c = callsomething(a)
yield twisted.internet.defer.succeed(None)
print callsomething2(b, c)
这个产量将立即返回到函数中(这意味着:它不会被重新安排,而是立即从产量继续)。这与 Tornado 的 tornado.gen.moment 形成对比(这不过是一个已经解决的 Future 与 None 的结果),这使得 yielder 重新安排自己,无论未来是否已经解决。
当产生像moment 这样的虚拟未来时,我如何运行像 Tornado 那样的行为?
【问题讨论】: