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. 【csp模拟赛5】限制 (restrict.cpp)--数学

    自己看吧: 爆搜代码: //春水初涨-春林初盛-春风十里-不如你 //----hzwer // 这是啥子题,读不懂-- //题意有问题 -- #include<iostream> #inc ...

  2. Java源码分析-UUID

    原文链接:Little Apple's Blog 本文分析的JDK版本为1.8.0_131. UUID? UUID是Universally Unique Identifier的缩写:Java UUID ...

  3. lyc——2019.10.31

    10:判决素数个数 总时间限制: 1000ms 内存限制: 65536kB 描述 输入两个整数X和Y,输出两者之间的素数个数(包括X和Y). 输入 两个整数X和Y(1 <= X,Y <= ...

  4. LINUX 字体查看 字体更改mkfontdir

    Linux下字体查看: #fc-list :lang=zh 字体更改: 首先找到相应的字体库:simsun.ttf 宋体 #mkdir -p /usr/share/fonts/truetype //创 ...

  5. 在docker 安装gitlab

    一.Centos 7 上安装 官方文档:https://docs.docker.com/install/linux/docker-ce/centos/ 1.安装环境      yum install  ...

  6. DS博客作业04--树大作业

    1.树的存储结构 本组采用的树的存储结构为链式结构,选择如图所示的结构体 Name为结点的名称 LevelNum为孩子节点的个数 *Children[20]用来指向不同的孩子结点(类似于二叉树的结构体 ...

  7. Flutter移动电商实战 --(5)dio基础_引入和简单的Get请求

    这篇开始我们学习Dart第三方Http请求库dio,这是国人开源的一个项目,也是国内用的最广泛的Dart Http请求库. 1.dio介绍和引入 dio是一个强大的Dart Http请求库,支持Res ...

  8. 3299 Humidex

    Humidex Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 23219   Accepted: 8264 Descript ...

  9. mysql的启动问题

    用cmd启动MySQL   (net start mysql )时出现(发生系统错误 5.  拒绝访问)这样的错误是因为cmd 权限太低了需要提高cmd权限才行(即使管理员权限) 如下图cmd所示: ...

  10. 1.springboot启动流程

    SpringBoot版本:2.1.2.RELEASE 1.maven <parent> <groupId>org.springframework.boot</groupI ...