DeferredList
有時候,你想等全部的事件都發生後通知你,而不是每個都通知一下。好比,你想等待在在一個列表裏的全部鏈接都關閉後通知你,twisted.internet.defer.DeferredList 可以完成你想要的功能。
爲了建立一個DeferredList從多個Deferreds,你只須要簡單的傳遞一個列表就能夠了: this
#Create a DeferredList
dl = defer.DeferredList([deferred1, deferred2, deferred3]) spa
你能夠把這個DeferredList當作一個原生的Deferred;你可以調用 addCallbacks等.DeferredList將調用它的callback當全部的deferreds完成的時候 three
例子 事件
from twisted.internet import defer get
def printResult(result):
for (success, value) in result:
if success:
print 'Success', value
else:
print 'Failure', value.getErrorMessage() it
deferred1 = defer.Deferred()
deferred2 = defer.Deferred()
deferred3 = defer.Deferred() io
dl = defer.DeferredList([deferred1, deferred2, deferred3], consumeErrors=True) import
dl.addCallback(printResult) List
deferred1.callback('one')
deferred2.errback(Exception('bang!!'))
deferred3.callback('three') im
結果:
# 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.