Differences between revisions 1 and 2
 ⇤ ← Revision 1 as of 2008-05-08 05:38:09 → Size: 2299 Editor: GlennTarbox Comment: ← Revision 2 as of 2008-06-27 16:50:47 → ⇥ Size: 2377 Editor: GlennTarbox Comment: Deletions are marked like this. Additions are marked like this. Line 1: Line 1: ## page was renamed from GlennTarbox/TwistedTalk/120 Callbacks and Deferreds

# Deferreds are Beautiful

```   1 from twisted.internet import reactor
2
3 # pedantic and gets nasty quickly
4
5 def main():
6     d = O.doLongCalculation()
8     return d                  # the pattern you'll end up following
9
10 def gotResult(result):
11     print "result is: ", result
12
13 reactor.callWhenRunning(main)
14 reactor.run()
15
16 ########################
17
18 # a little nicer
19
20 def main():
22
23 def gotResult(result):
24     print "result is: ", result
25
26 reactor.callWhenRunning(main)
27 reactor.run()
28
29 #######################
30
31 # making things a bit more pythonic
32
33 def main():
34     def gotResult(result):
35             print "result is: ", result
37
38 #######################
39
40 # deferreds are chains
41
42 def main():
43     def gotResult(result):
44             print "result is: ", result
45     d = O.doLongCalculation()
47     d.addCallback(lambda r: reactor.stop())  # throw away the result
48     return d
49
50 #####################
51
52 # making our own deferreds
53 import sys
54 from twisted.internet import reactor, defer
55 from twisted.python import log
56
57 def sleepyCalc(message):
58     log.msg("sleepyCalc: " + message)
59     d = defer.Deferred()
60     reactor.callLater(10.0, wakeyTime, d, message)
61     return d
62
63 def wakeyTime(d, message):
64     log.msg("wakeyTime: " + message)
65     d.callback(message)
66
67 def gotResult(result):
68     log.msg("gotResult: " + result)
69     return "-+- gotResult -+- " + result
70
71 def main(message):
72     log.msg("main message: " + message)
73     d=sleepyCalc(message)
75     d.addCallback(sleepyCalc)   # hmmm...