defer.py 971 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env python
  2. from twisted.internet import reactor, defer
  3. from pprint import pprint
  4. def getData(inputData):
  5. print('getData({0})'.format(inputData))
  6. deferred = defer.Deferred()
  7. # simulate a delayed result by asking reactor
  8. # to fire in 2 seconds with inputData * 3 as result
  9. reactor.callLater(2, deferred.callback, inputData * 3)
  10. return deferred
  11. def cbPrint(result):
  12. print("result: {0}".format(result))
  13. # doing eferred, or the return result + 1 works
  14. deferred = defer.Deferred()
  15. reactor.callLater(1, deferred.callback, result + 1)
  16. return deferred
  17. # return result + 1
  18. def cbPrint2(result):
  19. print("result:")
  20. pprint(result)
  21. return result + 2
  22. d = getData(3)
  23. # Ok, chaining callbacks is ... different.
  24. d.addCallback(cbPrint)
  25. # Before return result, this was printing None.
  26. d.addCallback(cbPrint2)
  27. d.addCallback(cbPrint)
  28. reactor.callLater(5, reactor.stop)
  29. print("starting the reactor")
  30. reactor.run()