理解twisted中的reactor和deferred(二)
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(二)的更多相关文章
- 理解twisted中的reactor和deferred(一)
Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理. 简单讲,当我们需要执行一个耗时操作,比 ...
- javascript中的promise和deferred:实践(二)
javascript中的promise和deferred:实践(二) 介绍: 在第一节呢,我花了大量的时间来介绍promises和deferreds的理论.现在呢,我们来看看jquery中的promi ...
- 如何理解T-SQL中Merge语句(二)
写在前面的话:上一篇写了如何理解T-SQL中Merge语句,基本把Merge语句要讲的给讲了,在文章的后面,抛出了几个结,当时没有想明白怎么去用文字表达,这一篇就来解答一下这几个结,又是一篇“天马行空 ...
- 理解函数式编程中的函数组合--Monoids(二)
使用函数式语言来建立领域模型--类型组合 理解函数式编程语言中的组合--前言(一) 理解函数式编程中的函数组合--Monoids(二) 继上篇文章引出<范畴论>之后,我准备通过几篇文章,来 ...
- 深入理解jQuery中的Deferred
引入 1 在开发的过程中,我们经常遇到某些耗时很长的javascript操作,并且伴随着大量的异步. 2 比如我们有一个ajax的操作,这个ajax从发出请求到接收响应需要5秒,在这5秒内我们可以 ...
- 深入理解JS中的对象(二):new 的工作原理
目录 序言 不同返回值的构造函数 深入 new 调用函数原理 总结 参考 1.序言 在 深入理解JS中的对象(一):原型.原型链和构造函数 中,我们分析了JS中是否一切皆对象以及对象的原型.原型链和构 ...
- Firefly distributed模块的原理与twisted中PB远程调用协议
这些天断断续续在看Firefly, 看了一下distributed模块的设计,其实就是使用的twisted.spread.pb觉得以后要是想用Firefly有必要了解一下twisted, 所以在网上查 ...
- 理解Twisted与非阻塞编程
先来看一段代码: # ~*~ Twisted - A Python tale ~*~ from time import sleep # Hello, I'm a developer and I mai ...
- Python Twisted系列教程14:Deferred用于同步环境
作者:dave@http://krondo.com/when-a-deferred-isnt/ 译者:杨晓伟(采用意译) 你可以从这里从头开始阅读这个系列. 介绍 这部分我们要介绍Deferred的 ...
随机推荐
- learning gcc #pragma once
referenc: https://zh.wikipedia.org/wiki/Pragma_once 在C和C++编程语言中,#pragma once是一个非标准但是被广泛支持的前置处理符号, 会让 ...
- P1359 租用游艇 && P3905 道路重建 ------Floyd算法
P1359 租用游艇 原题链接https://www.luogu.org/problemnew/show/P1359 P3905 道路重建 原题链接https://www.luogu.org/ ...
- 关于Map的问题
关于Map的问题主要有: (1)什么是散列表? (2)怎么实现一个散列表? (3)java中HashMap实现方式的演进? (4)HashMap的容量有什么特点? (5)HashMap是怎么进行扩容的 ...
- json常用的注解
json注解: 1.@JsonIgnoreProperties: 此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响. 写法将此标签加在model ...
- JDBC与ODBC
ODBC(Open Database Connectivity)是一组对数据库访问的标准API,这些API通过SQL来完成大部分任务,而且它本身也支持SQL语言,支持用户发来的SQL.ODBC定义了 ...
- Android 网络请求Retrofit + RxJava
一.背景 经常看到项目用Retrofit+RxJava+RxAndroid的框架,为了看懂项目的结构.现在来了解一下,Retrofit: Retrofit是Square 公司开发的一款正对Androi ...
- C++之ListNode
单链表,弄清楚可stl中list的区别 ListNode的结构 struct ListNode { int val; //当前结点的值 ListNode *next; //指向下一个结点的指针 Lis ...
- hive端建表中文注释乱码
背景:mysql编码是utf-8,mysql中建库建表中文显示都正常,但在hive窗口中建表时字段中文注释均乱码的问题. 问题:hive中建表后字段中文注释显示异常. 1. 定位 mysql 端问题 ...
- spring-kafka —— 生产者消费者重要配置
一.生产者配置 # 以逗号分隔的主机:端口对列表,用于建立与Kafka群集的初始连接 spring.kafka.producer.bootstrap-servers=TopKafka1:9092,To ...
- Spring Boot 2.0 集成 Druid 数据源
一.Maven项目依赖 <!-- 开发者工具(热部署 修改classpath下的文件springboot自动重启) --> <dependency> <groupId&g ...