Ver código fonte

updated the defer example, added links to the docs.

Steve Thielemann 5 anos atrás
pai
commit
a965bc3e7e
1 arquivos alterados com 17 adições e 5 exclusões
  1. 17 5
      defer.py

+ 17 - 5
defer.py

@@ -1,5 +1,8 @@
 #!/usr/bin/env python
 
+
+# https://twistedmatrix.com/documents/16.2.0/core/howto/defer.html
+
 from twisted.internet import reactor, defer
 from pprint import pprint
 
@@ -8,21 +11,26 @@ def getData(inputData):
     deferred = defer.Deferred()
     # simulate a delayed result by asking reactor
     # 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)
     return deferred
 
 def cbPrint(result):
-    print("result: {0}".format(result))
+    print("cbPrint({0})".format(result))
     # doing eferred, or the return result + 1 works
+    print("return result (x+1) in 1 sec...")
     deferred = defer.Deferred()
     reactor.callLater(1, deferred.callback, result + 1)
     return deferred
     # return result + 1
 
 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)
 # Ok, chaining callbacks is ... different.
@@ -31,8 +39,12 @@ d.addCallback(cbPrint)
 # Before return result, this was printing None.  
 d.addCallback(cbPrint2)
 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")
 reactor.run()
 
+
+print("Reactor has been safely shutdown.  :P")