Deferred可以添加多个回调函数,每个回调函数的结果作为下一个回调函数的参数

代码实例(可在pycharm中运行,摘自 https://twistedmatrix.com/documents/current/core/howto/defer.html

from twisted.internet import reactor, defer

class Getter:
def gotResults(self, x):
"""
The Deferred mechanism provides a mechanism to signal error
conditions. In this case, odd numbers are bad. This function demonstrates a more complex way of starting
the callback chain by checking for expected results and
choosing whether to fire the callback or errback chain
"""
if self.d is None:
print("Nowhere to put results")
return d = self.d
self.d = None
if x % 2 == 0:
d.callback(x*3)  # 执行d的第一个回调函数,也就是_toHTML函数
else:
d.errback(ValueError("You used an odd number!")) # 执行d的errorback回调函数,也就是ebPrintError def _toHTML(self, r):
"""
This function converts r to HTML. It is added to the callback chain by getDummyData in
order to demonstrate how a callback passes its own result
to the next callback
"""
return "Result: %s" % r  #返回给第二个回调cbPrintData函数做参数 def getDummyData(self, x):
"""
The Deferred mechanism allows for chained callbacks.
In this example, the output of gotResults is first
passed through _toHTML on its way to printData. Again this function is a dummy, simulating a delayed result
using callLater, rather than using a real asynchronous
setup.
"""
self.d = defer.Deferred()
# simulate a delayed result by asking the reactor to schedule
# gotResults in 2 seconds time
reactor.callLater(2, self.gotResults, x)  # 2秒后执行gotResults函数
self.d.addCallback(self._toHTML)  # 添加第一个回调函数
return self.d def cbPrintData(result):
print(result) def ebPrintError(failure):
import sys
sys.stderr.write(str(failure)) # this series of callbacks and errbacks will print an error message
g = Getter()
d = g.getDummyData(3)
d.addCallback(cbPrintData)
d.addErrback(ebPrintError) # this series of callbacks and errbacks will print "Result: 12"
g = Getter()
d = g.getDummyData(4)
d.addCallback(cbPrintData) # 添加第二个回调函数
d.addErrback(ebPrintError) reactor.callLater(4, reactor.stop)
reactor.run()

 

结果:

官网示例图片:这里的Data Source就是 gotResults 函数,执行Deferred 的callback函数相当于把result给到callback模块,结果一级一级传递给所有的callback函数,任何一级callback出现错误,都将调用errback函数

同时,如果errback没有返回exception 或者 return a twisted.python.failure.Failure instance,将切回callback继续执行

理解twisted中的reactor和deferred(二)的更多相关文章

  1. 理解twisted中的reactor和deferred(一)

    Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理. 简单讲,当我们需要执行一个耗时操作,比 ...

  2. javascript中的promise和deferred:实践(二)

    javascript中的promise和deferred:实践(二) 介绍: 在第一节呢,我花了大量的时间来介绍promises和deferreds的理论.现在呢,我们来看看jquery中的promi ...

  3. 如何理解T-SQL中Merge语句(二)

    写在前面的话:上一篇写了如何理解T-SQL中Merge语句,基本把Merge语句要讲的给讲了,在文章的后面,抛出了几个结,当时没有想明白怎么去用文字表达,这一篇就来解答一下这几个结,又是一篇“天马行空 ...

  4. 理解函数式编程中的函数组合--Monoids(二)

    使用函数式语言来建立领域模型--类型组合 理解函数式编程语言中的组合--前言(一) 理解函数式编程中的函数组合--Monoids(二) 继上篇文章引出<范畴论>之后,我准备通过几篇文章,来 ...

  5. 深入理解jQuery中的Deferred

    引入 1  在开发的过程中,我们经常遇到某些耗时很长的javascript操作,并且伴随着大量的异步. 2  比如我们有一个ajax的操作,这个ajax从发出请求到接收响应需要5秒,在这5秒内我们可以 ...

  6. 深入理解JS中的对象(二):new 的工作原理

    目录 序言 不同返回值的构造函数 深入 new 调用函数原理 总结 参考 1.序言 在 深入理解JS中的对象(一):原型.原型链和构造函数 中,我们分析了JS中是否一切皆对象以及对象的原型.原型链和构 ...

  7. Firefly distributed模块的原理与twisted中PB远程调用协议

    这些天断断续续在看Firefly, 看了一下distributed模块的设计,其实就是使用的twisted.spread.pb觉得以后要是想用Firefly有必要了解一下twisted, 所以在网上查 ...

  8. 理解Twisted与非阻塞编程

    先来看一段代码: # ~*~ Twisted - A Python tale ~*~ from time import sleep # Hello, I'm a developer and I mai ...

  9. Python Twisted系列教程14:Deferred用于同步环境

    作者:dave@http://krondo.com/when-a-deferred-isnt/  译者:杨晓伟(采用意译) 你可以从这里从头开始阅读这个系列. 介绍 这部分我们要介绍Deferred的 ...

随机推荐

  1. g++版本低于4.7使用C++11

    编译时需要添加: 需要添加头文件#include<memory> g++ -std=gnu++0x share_ptr.cpp -o s 原文: C++11 features are av ...

  2. Eclipse一直building workspace问题解决

    今天新导入了一个maven项目,但是总是一直building workspace 解决方案: 去掉图中Maven  Project Builder勾选

  3. BZOJ1005--[HNOI2008]明明的烦恼(树的prufer编码)

    1005: [HNOI2008]明明的烦恼 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 5768  Solved: 2253[Submit][Stat ...

  4. Java后台开发精选知识图谱

    1.引言: 学习一个新的技术时,其实不在于跟着某个教程敲出了几行.几百行代码,这样你最多只能知其然而不知其所以然,进步缓慢且深度有限,最重要的是一开始就对整个学习路线有宏观.简洁的认识,确定大的学习方 ...

  5. Redis 延迟指标监控

    Redis 延迟监控框架 Redis 2.8.13 引入了Latency Monitoring的一个新功能,可以帮助我们检查和排查引起延迟的原因. Latecny Monitoring 由如下组成: ...

  6. 使用selenium IDE 等一系列需要下载的东西的地址

    转载来自:http://blog.csdn.net/u012246342/article/details/53005730 selenium 官网 IDE 等一系列 下载地址:http://www.s ...

  7. php中的<?= ?>和<?php ?>有什么区别么?

    <? ?>是短标签<?php ?>是长标签在php的配置文件(php.ini)中有一个short_open_tag的值,开启以后可以使用PHP的短标签:<? ?>同 ...

  8. Django中三种方式写form表单

    除了在html中自己手写form表单外,django还可以通过 继承django.forms.Form 或django.forms.ModelForm两个类来自动生成form表单,下面依次利用三种方式 ...

  9. UDDI:百科

    ylbtech-UDDI:百科 UDDI是一种用于描述.发现.集成Web Service的技术,它是Web Service协议栈的一个重要部分.通过UDDI,企业可以根据自己的需要动态查找并使用Web ...

  10. Android : 供应商原生开发套件 (VNDK)

    一.VNDK概述 VNDK(Vendor Native Development Kit)是一组专门用于vendor实现其HAL的lib库,因为自Android 8.0以来,Google引入了Trebl ...