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