What is the significance of the decorators
@reactor.callWhenRunning,
@results_deferred.addCallback
@results_deferred.addErrback.
Also what are deferred strings, for example in the
twisted.internet.utils.getProcessOutput()
returns a deferred string what exactly is happening here?
I am new to twisted hence this might be a very simple question but reading twisted documentation did not help me much
In the normal programming practice you'd do
db = Database.connect()
result = db.getResult()
processResult(result)
Now depending on your Database and network, these 3 statements can take anywhere from a millisecond to a few seconds.
We've all been programming this way for decades now, and for the most part we're fine with 'waiting'.
But there comes a time when your program cant just wait for results. You'd start to think, gee I could do a lot of other things while I wait for the result. Maybe print an output, or process a function, or just quickly check the socket etc.
Enter Twisted and Deferred.
Instead of waiting for result, in Twisted when invoked the special methods you'll get a Deferred. You'll add a callback function to this deferred which means, call this function when you have the result/answer.
deferredResult = db.nonBlockingGetResult()
deferredResult.addCallback(processOutput)
As soon as the first statement is executed, it returns the 'something' back. And that something is Deferred. There's no blocking there, there no waiting. And to this Deferred you add the callback processOutput which is called when deferred is 'fired' - ie result is ready.
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With