5 ms·
Deferreds in Twisted make it easy to chain asynchronous code with error handling together: def parseData(data): return doManyFancyThingsWith(data)
by eurleif 14y ago
Deferreds in Twisted make it easy to chain asynchronous code with error handling together:
def parseData(data):
return doManyFancyThingsWith(data)
def parsedAsyncResult():
return asyncResult().addCallback(parseData)
def callback(data):
print 'Parsed data:', data
def errback(err):
print 'Oh no, something went wrong!'
parsedAsyncResult().addCallbacks(callback, errback)
If an error is raised by either asyncResult() or parseData(), it will be caught by the errback function, even though parsedAsyncResult() didn't explicitly do anything to pass errors along.
- pjscott 14y agoThat looks like an unnecessarily confusing way of writing this code: try: data = doManyFancyThingsWith(asyncResult()) print 'Parsed data:', data except: print 'Oh no, something went wrong!' That's the code I would write if I were using Eventlet or Gevent, and it would work just fine. Why settle for less? It's 2012, damn it; we shouldn't have to dick around with deferreds except under exotic circumstances.
- zenbot 14y agoThis is possible in Twisted, using inline callbacks: try: data = doManyFancyThingsWith(yield asyncResult()) print 'Parsed data:', data except: print 'Oh no, something went wrong!' I find that I use inline callbacks for the common case and work with deferreds directly only when it makes more sense to handle callbacks explicitly.