3
# Copyright (c) 2009 Twisted Matrix Laboratories.
4
# See LICENSE for details.
6
from twisted.internet import defer
7
from twisted.python import failure, util
10
The deferred callback chain is stateful, and can be executed before
11
or after all callbacks have been added to the chain
14
class Counter(object):
19
print "we got an exception: %s" % (f.getTraceback(),)
22
def handleResult(result):
24
print "callback %s" % (Counter.num,)
25
print "\tgot result: %s" % (result,)
26
return "yay! handleResult was successful!"
28
def failAtHandlingResult(result):
30
print "callback %s" % (Counter.num,)
31
print "\tgot result: %s" % (result,)
32
print "\tabout to raise exception"
33
raise RuntimeError, "whoops! we encountered an error"
35
def deferredExample1():
36
# this is another common idiom, since all add* methods
37
# return the deferred instance, you can just chain your
38
# calls to addCallback and addErrback
40
d = defer.Deferred().addCallback(failAtHandlingResult
41
).addCallback(handleResult
42
).addErrback(handleFailure)
46
def deferredExample2():
51
d.addCallback(failAtHandlingResult)
52
d.addCallback(handleResult)
53
d.addErrback(handleFailure)
56
if __name__ == '__main__':
58
print "\n-------------------------------------------------\n"