How do I attach two separate callbacks to a Twisted deferred, so both fire after the result is ready?

StackOverflow https://stackoverflow.com//questions/24051762

  •  21-12-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top