<p>回调(默认情况下)是同步的。然而,正如<a href="http://twistedmatrix.com/documents/current/core/howto/defer.html" rel="noreferrer">Twisted doc</a>所指出的:</p>
<blockquote>
<p>If you need one Deferred to wait on another, all you need to do is return a Deferred from a method added to addCallbacks.</p>
</blockquote>
<p>因此可以使用它在回调链中执行一些异步处理。让我们这样做:</p>
<pre><code>from twisted.internet import reactor, defer
def callback_func_2(result, previous_data):
# here we pass the result of the deferred down the callback chain
# (done synchronously)
print "calling function 1 on result:%s with previous result:%s" % (result, previous_data)
return result
def callback_func(result):
#let's do some asynchronous stuff in this callback
# simple trick here is to return a deferred from a callback
# instead of the result itself.
#
# so we can do asynchronous stuff here,
# like firing something 1 second later and have
# another method processing the result
print "calling function 1 on result:%s" % result
d = defer.Deferred()
reactor.callLater(1, d.callback, "second callback")
d.addCallback(callback_func_2, result)
return d
def do():
d = defer.Deferred()
reactor.callLater(1, d.callback, "first callback")
d.addCallback(callback_func)
return d
do()
reactor.run()
</code></pre>