defer.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python
  2. # https://twistedmatrix.com/documents/16.2.0/core/howto/defer.html
  3. from twisted.internet import reactor, defer
  4. from pprint import pprint
  5. def getData(inputData):
  6. print('getData({0})'.format(inputData))
  7. deferred = defer.Deferred()
  8. # simulate a delayed result by asking reactor
  9. # to fire in 2 seconds with inputData * 3 as result
  10. print("return result (x*3) in 2 sec...")
  11. reactor.callLater(2, deferred.callback, inputData * 3)
  12. return deferred
  13. def cbPrint(result):
  14. print("cbPrint({0})".format(result))
  15. # doing eferred, or the return result + 1 works
  16. print("return result (x+1) in 1 sec...")
  17. deferred = defer.Deferred()
  18. reactor.callLater(1, deferred.callback, result + 1)
  19. return deferred
  20. # return result + 1
  21. def cbPrint2(result):
  22. print("cbPrint2({0})".format(result))
  23. print("return result (x+2) ...")
  24. # print("(this isn't a defer)") # it is now! :P
  25. # return a Deferred object already called back with the value of result
  26. return defer.succeed(result + 2)
  27. # return result + 2
  28. d = getData(3)
  29. # Ok, chaining callbacks is ... different.
  30. d.addCallback(cbPrint)
  31. # Before return result, this was printing None.
  32. d.addCallback(cbPrint2)
  33. d.addCallback(cbPrint)
  34. d.addCallback(print)
  35. print("Stop the reactor in 7 seconds...")
  36. reactor.callLater(7, reactor.stop)
  37. print("starting the reactor")
  38. reactor.run()
  39. print("Reactor has been safely shutdown. :P")