Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理。
简单讲,当我们需要执行一个耗时操作,比如下载某个大图片,此时用twisted的异步http请求,会给我们返回一个Deferred对象,让我们可以不用在这等图片下载完成,当前线程不会阻塞,而是可以去处理别的逻辑。twisted有一个底层event loop(类似tornado ioloop)处理线程),等图片下载完成后,会去自动触发Deferred的回调操作,这个细节我们不需要操作,我们要做的,就是添加这个回调逻辑,也就是常说的注册回调。(摘自:https://www.cnblogs.com/mactec/p/9850665.html)
实例代码(可在pycharm中运行):
from twisted.internet import reactor, defer def getDummyData(inputData): """ This function is a dummy which simulates a delayed result and returns a Deferred which will fire with that result. Don't try too hard to understand this. """ print('getDummyData called') deferred = defer.Deferred() # simulate a delayed result by asking the reactor to fire the # Deferred in 2 seconds time with the result inputData * 3 reactor.callLater(2, deferred.callback, inputData * 3) # 表示2秒后执行Deferred的回调函数,回调函数的参数是第三个参数 return deferred def cbPrintData(result): """ Data handling function to be added as a callback: handles the data by printing the result """ print('Result received: {}'.format(result)) deferred = getDummyData(3) deferred.addCallback(cbPrintData) # manually set up the end of the process by asking the reactor to # stop itself in 4 seconds time reactor.callLater(4, reactor.stop) # 4秒后停止reactor # start up the Twisted reactor (event loop handler) manually print('Starting the reactor') reactor.run()
结果如下: