[Twisted-Python] problem with combining deferreds together
Jason Fritcher
fritcher at corp.earthlink.net
Mon Aug 15 13:13:44 EDT 2005
michal salaban wrote:
> class ObjectRepository:
>
> def getById(self, id):
> dMain = self.dbpool.runInteraction(
> fetchOneAndMapToDictionary,
> "SELECT * FROM MainTable WHERE id = '%d'" % (id,)
> )
> dMain.addCallback(self._gotMainData)
> return dMain
>
> def _gotMainData(self, mappedRow):
> dSub = self.dbpool.runInteraction(
> fetchOneAndMapToDictionary,
> "SELECT * FROM SubTable WHERE id = '%d'" % (mappedRow['SubID'],)
> )
> dSub.addCallback(self._gotSubData)
> return [what to return ????]
>
>
> how can i return the result that consist of data from both queries?
> chaining callbacks is impossible. i cannot have dSub before dMain.callback()
> is called, and also cannot do dMain.chainDeferred(dSub) in _gotMainData()
> because dMain has already been returned to calling code and contains callbacks
> attached there.
Give this a try and see how it works for you...
def _gotMainData(self, mappedRow):
dSub = self.dbpool.runInteraction(
fetchOneAndMapToDictionary,
"SELECT * FROM SubTable WHERE id = '%d'" % (mappedRow['SubID'],)
)
dSub.addCallback(self._gotSubData, mappedRow)
return dSub
def _gotSubData(self, subMappedRow, mainMappedRow):
# Do work here.
When adding callbacks to a deferred, you can add arguments that will get
passed to the argument, independant of the result from previous
callbacks. Like above, you can take the mappedRow dictionary from the
first callback and pass it as an argument to the callback for the
subrequest. Also, for the new deferred to be useful, you return it from
the callback. When Twisted sees that, it'll pause the callback chain
until that deferred fires and processes all of its callbacks. It'll take
the result that is produced from that deferred and use it as the result
for the next callback in the main deferred.
--
Jason Fritcher
Software Engineer
Core Infrastructure Services & Strategy
Earthlink, Inc
fritcher at corp.earthlink.net
(404) 748-7262, x22262
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 253 bytes
Desc: OpenPGP digital signature
Url : http://twistedmatrix.com/pipermail/twisted-python/attachments/20050815/0d71fccb/attachment.pgp
More information about the Twisted-Python
mailing list