DeferredList
有时候,你想等所有的事件都发生后通知你,而不是每一个都通知一下。比如,你想等待在在一个列表里的所有连接都关闭后通知你,twisted.internet.defer.DeferredList 能够完成你想要的功能。
为了创建一个DeferredList从多个Deferreds,你只需要简单的传递一个列表就可以了:
#Create a DeferredList
dl = defer.DeferredList([deferred1, deferred2, deferred3])
你可以把这个DeferredList当做一个原生的Deferred;你能够调用 addCallbacks等.DeferredList将调用它的callback当所有的deferreds完成的时候
例子
from twisted.internet import defer
def printResult(result):
for (success, value) in result:
if success:
print 'Success', value
else:
print 'Failure', value.getErrorMessage()
deferred1 = defer.Deferred()
deferred2 = defer.Deferred()
deferred3 = defer.Deferred()
dl = defer.DeferredList([deferred1, deferred2, deferred3], consumeErrors=True)
dl.addCallback(printResult)
deferred1.callback('one')
deferred2.errback(Exception('bang!!'))
deferred3.callback('three')
结果:
# Success: on
# Failure: bang!
# Success: three
一个标准的DeferredList 应该从来不要调用errback,但是failures在Deferreds会被传递到DeferredList会任然errorback除非consumeError 被设置为True
def printResult(result):
print result
def addTen(result):
return result + " ten"
# Deferred gets callback before DeferredList is created
deferred1 = defer.Deferred()
deferred2 = defer.Deferred()
deferred1.addCallback(addTen)
dl = defer.DeferredList([deferred1, deferred2])
dl.addCallback(printResult)
deferred1.callback("one") # fires addTen, checks DeferredList, stores "one ten"
deferred2.callback("two")
#[(True, 'one ten'), (True, 'two')]
deferred1 = defer.Deferred()
deferred2 = defer.Deferred()
dl = defer.DeferredList([deferred1, deferred2])
deferred1.addCallback(addTen) # will run*after*DeferredList gets its value
dl.addCallback(printResult)
deferred1.callback("one") # checks DeferredList, stores "one", fires addTen
deferred2.callback("two")
# At this point, dl will fire its callback, printing:
# [(1, ’one), (1, ’two’)]
参数consumeErrors和DeferredList有同样的意义。如果为true,gatherResult会拒绝所有的错误
在Deferreds里的。你应该总是使用这个参数,除非你想更深层的调用,或者你知道他们永远不会出错。
否则会发生一个未知错误,并被twisted记录进log.