|
@@ -1,5 +1,8 @@
|
|
#!/usr/bin/env python
|
|
#!/usr/bin/env python
|
|
|
|
|
|
|
|
+
|
|
|
|
+# https://twistedmatrix.com/documents/16.2.0/core/howto/defer.html
|
|
|
|
+
|
|
from twisted.internet import reactor, defer
|
|
from twisted.internet import reactor, defer
|
|
from pprint import pprint
|
|
from pprint import pprint
|
|
|
|
|
|
@@ -8,21 +11,26 @@ def getData(inputData):
|
|
deferred = defer.Deferred()
|
|
deferred = defer.Deferred()
|
|
# simulate a delayed result by asking reactor
|
|
# simulate a delayed result by asking reactor
|
|
# to fire in 2 seconds with inputData * 3 as result
|
|
# to fire in 2 seconds with inputData * 3 as result
|
|
|
|
+ print("return result (x*3) in 2 sec...")
|
|
reactor.callLater(2, deferred.callback, inputData * 3)
|
|
reactor.callLater(2, deferred.callback, inputData * 3)
|
|
return deferred
|
|
return deferred
|
|
|
|
|
|
def cbPrint(result):
|
|
def cbPrint(result):
|
|
- print("result: {0}".format(result))
|
|
|
|
|
|
+ print("cbPrint({0})".format(result))
|
|
# doing eferred, or the return result + 1 works
|
|
# doing eferred, or the return result + 1 works
|
|
|
|
+ print("return result (x+1) in 1 sec...")
|
|
deferred = defer.Deferred()
|
|
deferred = defer.Deferred()
|
|
reactor.callLater(1, deferred.callback, result + 1)
|
|
reactor.callLater(1, deferred.callback, result + 1)
|
|
return deferred
|
|
return deferred
|
|
# return result + 1
|
|
# return result + 1
|
|
|
|
|
|
def cbPrint2(result):
|
|
def cbPrint2(result):
|
|
- print("result:")
|
|
|
|
- pprint(result)
|
|
|
|
- return result + 2
|
|
|
|
|
|
+ print("cbPrint2({0})".format(result))
|
|
|
|
+ print("return result (x+2) ...")
|
|
|
|
+ # print("(this isn't a defer)") # it is now! :P
|
|
|
|
+ # return a Deferred object already called back with the value of result
|
|
|
|
+ return defer.succeed(result + 2)
|
|
|
|
+ # return result + 2
|
|
|
|
|
|
d = getData(3)
|
|
d = getData(3)
|
|
# Ok, chaining callbacks is ... different.
|
|
# Ok, chaining callbacks is ... different.
|
|
@@ -31,8 +39,12 @@ d.addCallback(cbPrint)
|
|
# Before return result, this was printing None.
|
|
# Before return result, this was printing None.
|
|
d.addCallback(cbPrint2)
|
|
d.addCallback(cbPrint2)
|
|
d.addCallback(cbPrint)
|
|
d.addCallback(cbPrint)
|
|
|
|
+d.addCallback(print)
|
|
|
|
|
|
-reactor.callLater(5, reactor.stop)
|
|
|
|
|
|
+print("Stop the reactor in 7 seconds...")
|
|
|
|
+reactor.callLater(7, reactor.stop)
|
|
print("starting the reactor")
|
|
print("starting the reactor")
|
|
reactor.run()
|
|
reactor.run()
|
|
|
|
|
|
|
|
+
|
|
|
|
+print("Reactor has been safely shutdown. :P")
|