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
Now we'll see what happens when you use 'addBoth'.
13
class Counter(object):
19
print "we got an exception: %s" % (f.getTraceback(),)
21
return "okay, continue on"
23
def handleResult(result):
25
print "callback %s" % (Counter.num,)
26
print "\tgot result: %s" % (result,)
27
return "yay! handleResult was successful!"
29
def failAtHandlingResult(result):
31
print "callback %s" % (Counter.num,)
32
print "\tgot result: %s" % (result,)
33
print "\tabout to raise exception"
34
raise RuntimeError, "whoops! we encountered an error"
36
def doThisNoMatterWhat(arg):
38
print "both %s" % (Counter.num,)
39
print "\tgot argument %r" % (arg,)
40
print "\tdoing something very important"
41
# we pass the argument we received to the next phase here
46
def behindTheScenes(result):
47
# equivalent to d.callback(result)
49
if not isinstance(result, failure.Failure): # ---- callback
51
result = handleResult(result)
53
result = failure.Failure()
58
if not isinstance(result, failure.Failure): # ---- callback
60
result = failAtHandlingResult(result)
62
result = failure.Failure()
67
# ---- this is equivalent to addBoth(doThisNoMatterWhat)
69
if not isinstance(result, failure.Failure):
71
result = doThisNoMatterWhat(result)
73
result = failure.Failure()
76
result = doThisNoMatterWhat(result)
78
result = failure.Failure()
81
if not isinstance(result, failure.Failure): # ---- callback
85
result = handleFailure(result)
87
result = failure.Failure()
90
def deferredExample():
92
d.addCallback(handleResult)
93
d.addCallback(failAtHandlingResult)
94
d.addBoth(doThisNoMatterWhat)
95
d.addErrback(handleFailure)
100
if __name__ == '__main__':
101
behindTheScenes("success")
102
print "\n-------------------------------------------------\n"