Reputation: 243
I am not very experienced with Twisted, but here is what I understand so far.
When I do a database query such as:
db = database.veryLongQuery(sql, binds)
I can add callbacks to do something with the result,
db.addCallback(lambda res: dispalyResult(res))
Otherwise if I need to do multiple things to the same result, I could make a method:
def doTwoThings(self, res):
self.d1 = anotherDeferred(res) # write to table A, return lastRowId
self.d2 = yetAnotherDeferred(res) # write to table B, return lastRowId
return d1
and attach that to db
(as the first callback)
db.addCallback(self.doTwoThings)
However, I would like to have a reference to d1
and d2
right from the start, at the same time as when db is created, since other events will be happening and I need to add callbacks to d1
and d2
.
How would I go about attaching two (or more) separate callback chains onto the same deferred, db
, so it 'splits', and both are fired side by side once the result is ready?
This way I can keep track of each deferred from the start and access them as necessary.
Or, is there way to create d1
and d2
from the start, so I have access to those names?
Upvotes: 2
Views: 533
Reputation: 1671
You may use something like this:
def splitResults(d1, d2):
def splitter(val):
# Pass val to d2 chain
d2.callback(val)
# Return val into d1's chain
return val
def splitterError(err):
d2.errback(err)
d1.addCallbacks(splitter, splitterError)
So, whenever d1 gets result, it will pass it to d2 too.
Upvotes: 1