- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我开始在一个需要异步编程的项目中使用 Twisted,并且文档非常好。
所以我的问题是,Twisted 中的 Deferred 与 Javascript 中的 Promise 是否相同?如果不是,有什么区别?
最佳答案
您的问题的答案都是 是 和 没有 取决于你问的原因。
是的:
两者都是扭曲的Deferred
和 Javascript Promise
实现一种机制,使同步代码块以给定的顺序运行,同时与其他同步代码块分离。
不:
所以 Javascript 的 Promise
实际上更类似于 Python 的 Future
,而解释这一点的通灵方式是谈论 Promise
和 Resolver
组合成 Deferred
,并声明这会影响您可以对回调执行的操作。
这一切都非常好,因为它是准确的,但是它并没有真正让任何事情变得更清楚,而且没有输入数千个几乎肯定会出错的单词,我可能最好引用一个知道的人关于 Python 的一些小知识。
Guido van Rossum on Deferreds:
Here's my attempt to explain Deferred's big ideas (and there are a lot of them) to advanced Python users with no previous Twisted experience. I also assume you have thought about asynchronous calls before. Just to annoy Glyph, I am using a 5-star system to indicate the importance of ideas, where 1 star is "good idea but pretty obvious" and 5 stars is "brilliant".
I am showing a lot of code snippets, because some ideas are just best expressed that way -- but I intentionally leave out lots of details, and sometimes I show code that has bugs, if fixing them would reduce understanding the idea behind the code. (I will point out such bugs.) I am using Python 3.
Notes specifically for Glyph: (a) Consider this a draft for a blog post. I'd be more than happy to take corrections and suggestions for improvements. (b) This does not mean I am going to change Tulip to a more Deferred-like model; but that's for a different thread.
Idea 1: Return a special object instead of taking a callback argument
When designing APIs that produce results asynchronously, you find that you need a system for callbacks. Usually the first design that comes to mind is to pass in a callback function that will be called when the async operation is complete. I've even seen designs where if you don't pass in a callback the operation is synchronous -- that's bad enough I'd give it zero stars. But even the one-star version pollutes all APIs with extra arguments that have to be passed around tediously. Twisted's first big idea then is that it's better to return a special object to which the caller can add a callback after receiving it. I give this three stars because from it sprout so many of the other good ideas. It is of course similar to the idea underlying the Futures and Promises found in many languages and libraries, e.g. Python's concurrent.futures (PEP 3148, closely following Java Futures, both of which are meant for a threaded world) and now Tulip (PEP 3156, using a similar design adapted for thread-less async operation).
Idea 2: Pass results from callback to callback
I think it's best to show some code first:
class Deferred:
def __init__(self):
self.callbacks = []
def addCallback(self, callback):
self.callbacks.append(callback) # Bug here
def callback(self, result):
for cb in self.callbacks:
result = cb(result)The most interesting bits are the last two lines: the result of each callback is passed to the next. This is different from how things work in concurrent.futures and Tulip, where the result (once set) is fixed as an attribute of the Future. Here the result can be modified by each callback.
This enables a new pattern when one function returning a Deferred calls another one and transforms its result, and this is what earns this idea three stars. For example, suppose we have an async function that reads a set of bookmarks, and we want to write an async function that calls this and then sorts the bookmarks. Instead of inventing a mechanism whereby one async function can wait for another (which we will do later anyway :-), the second async function can simply add a new callback to the Deferred returned by the first one:
def read_bookmarks_sorted():
d = read_bookmarks()
d.addCallback(sorted)
return dThe Deferred returned by this function represents a sorted list of bookmarks. If its caller wants to print those bookmarks, it must add another callback:
d = read_bookmarks_sorted()
d.addCallback(print)In a world where async results are represented by Futures, this same example would require two separate Futures: one returned by read_bookmarks() representing the unsorted list, and a separate Future returned by read_bookmarks_sorted() representing the sorted list.
There is one non-obvious bug in this version of the class: if addCallback() is called after the Deferred has already fired (i.e. its callback() method was called) then the callback added by addCallback() will never be called. It's easy enough to fix this, but tedious, and you can look it up in the Twisted source code. I'll carry this bug through successive examples -- just pretend that you live in a world where the result is never ready too soon. There are other problems with this design too, but I'd rather call the solutions improvements than bugfixes.
Aside: Twisted's poor choices of terminology
I don't know why, but, starting with the project's own name, Twisted often rubs me the wrong way with its choice of names for things. For example, I really like the guideline that class names should be nouns. But 'Deferred' is an adjective, and not just any adjective, it's a verb's past participle (and an overly long one at that :-). And why is it in a module named twisted.internet?
Then there is 'callback', which is used for two related but distinct purposes: it is the preferred term used for a function that will be called when a result is ready, but it is also the name of the method you call to "fire" the Deferred, i.e. set the (initial) result.
Don't get me started on the neologism/portmanteau that is 'errback', which leads us to...
Idea 3: Integrated error handling
This idea gets only two stars (which I'm sure will disappoint many Twisted fans) because it confused me a lot. I've also noted that the Twisted docs have some trouble explaining how it works -- In this case particularly I found that reading the code was more helpful than the docs.
The basic idea is simple enough: what if the promise of firing the Deferred with a result can't be fulfilled? When we write
d = pod_bay_doors.open()
d.addCallback(lambda _: pod.launch())how is HAL 9000 supposed to say "I'm sorry, Dave. I'm afraid I can't do that" ?
And even if we don't care for that answer, what should we do if one of the callbacks raises an exception?
Twisted's solution is to bifurcate each callback into a callback and an 'errback'. But that's not all -- in order to deal with exceptions raised by callbacks, it also introduces a new class, 'Failure'. I'd actually like to introduce the latter first, without introducing errbacks:
class Failure:
def __init__(self):
self.exception = sys.exc_info()[1](By the way, great class name. And I mean this, I'm not being sarcastic.)
Now we can rewrite the callback() method as follows:
def callback(self, result):
for cb in self.callbacks:
try:
result = cb(result)
except:
result = Failure()This in itself I'd give two stars; the callback can use isinstance(result, Failure) to tell regular results apart from failures.
By the way, in Python 3 it might be possible to do away with the separate Failure class encapsulating exceptions, and just use the built-in BaseException class. From reading the comments in the code, Twisted's Failure class mostly exists so that it can hold all the information returned by sys.exc_info(), i.e. exception class/type, exception instance, and traceback but in Python 3, exception objects already hold a reference to the traceback.There is some debug stuff that Twisted's Failure class does which standard exceptions don't, but still, I think most reasons for introducing a separate class have been addressed.
But let's not forget about the errbacks. We change the list of callbacks to a list of pairs of callback functions, and we rewrite the callback() method again, as follows:
def callback(self, result):
for (cb, eb) in self.callbacks:
if isinstance(result, Failure):
cb = eb # Use errback
try:
result = cb(result)
except:
result = Failure()For convenience we also add an errback() method:
def errback(self, fail=None):
if fail is None:
fail = Failure()
self.callback(fail)(The real errback() function has a few more special cases, it can be called with either an exception or a Failure as argument, and the Failure class takes an optional exception argument to prevent it from using sys.exc_info(). But none of that is essential and it makes the code snippets more complicated.)
In order to ensure that self.callbacks is a list of pairs we must also update addCallback() (it still doesn't work right when called after the Deferred has fired):
def addCallback(self, callback, errback=None):
if errback is None:
errback = lambda r: r
self.callbacks.append((callback, errback))If this is called with just a callback function, the errback will be a dummy that passes the result (i.e. a Failure instance) through unchanged. This preserves the error condition for a subsequent error handler. To make it easy to add an error handler without also handling a regular resullt, we add addErrback(), as follows:
def addErrback(self, errback):
self.addCallback(lambda r: r, errback)Here, the callback half of the pair will pass the (non-Failure) result through unchanged to the next callback.
If you want the full motivation, read Twisted's Introduction to Deferreds; I'll just end by noting that an errback and substitute a regular result for a Failure just by returning a non-Failure value (including None).
Before I move on to the next idea, let me point out that there are more niceties in the real Deferred class. For example, you can specify additional arguments to be passed to the callback and errback. But in a pinch you can do this with lambdas, so I'm leaving it out, because the extra code for doing the administration doesn't elucidate the basic ideas.
Idea 4: Chaining Deferreds
This is a five-star idea! Sometimes it really is necessary for a callback to wait for an additional async event before it can produce the desired result. For example, suppose we have two basic async operations, read_bookmarks() and sync_bookmarks(), and we want a combined operation. If this was synchronous code, we could write:
def sync_and_read_bookmarks():
sync_bookmarks()
return read_bookmarks()But how do we write this if all operations return Deferreds? With the idea of chaining, we can do it as follows:
def sync_and_read_bookmarks():
d = sync_bookmarks()
d.addCallback(lambda unused_result: read_bookmarks())
return dThe lambda is needed because all callbacks are called with a result value, but read_bookmarks() takes no arguments.
关于javascript - Twisted 的 Deferred 和 JavaScript 中的 Promise 一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375321/
我想做的是让 JTextPane 在 JPanel 中占用尽可能多的空间。对于我使用的 UpdateInfoPanel: public class UpdateInfoPanel extends JP
我在 JPanel 中有一个 JTextArea,我想将其与 JScrollPane 一起使用。我正在使用 GridBagLayout。当我运行它时,框架似乎为 JScrollPane 腾出了空间,但
我想在 xcode 中实现以下功能。 我有一个 View Controller 。在这个 UIViewController 中,我有一个 UITabBar。它们下面是一个 UIView。将 UITab
有谁知道Firebird 2.5有没有类似于SQL中“STUFF”函数的功能? 我有一个包含父用户记录的表,另一个表包含与父相关的子用户记录。我希望能够提取用户拥有的“ROLES”的逗号分隔字符串,而
我想使用 JSON 作为 mirth channel 的输入和输出,例如详细信息保存在数据库中或创建 HL7 消息。 简而言之,输入为 JSON 解析它并输出为任何格式。 最佳答案 var objec
通常我会使用 R 并执行 merge.by,但这个文件似乎太大了,部门中的任何一台计算机都无法处理它! (任何从事遗传学工作的人的附加信息)本质上,插补似乎删除了 snp ID 的 rs 数字,我只剩
我有一个以前可能被问过的问题,但我很难找到正确的描述。我希望有人能帮助我。 在下面的代码中,我设置了varprice,我想添加javascript变量accu_id以通过rails在我的数据库中查找记
我有一个简单的 SVG 文件,在 Firefox 中可以正常查看 - 它的一些包装文本使用 foreignObject 包含一些 HTML - 文本包装在 div 中:
所以我正在为学校编写一个 Ruby 程序,如果某个值是 1 或 3,则将 bool 值更改为 true,如果是 0 或 2,则更改为 false。由于我有 Java 背景,所以我认为这段代码应该有效:
我做了什么: 我在这些账户之间创建了 VPC 对等连接 互联网网关也连接到每个 VPC 还配置了路由表(以允许来自双方的流量) 情况1: 当这两个 VPC 在同一个账户中时,我成功测试了从另一个 La
我有一个名为 contacts 的表: user_id contact_id 10294 10295 10294 10293 10293 10294 102
我正在使用 Magento 中的新模板。为避免重复代码,我想为每个产品预览使用相同的子模板。 特别是我做了这样一个展示: $products = Mage::getModel('catalog/pro
“for”是否总是检查协议(protocol)中定义的每个函数中第一个参数的类型? 编辑(改写): 当协议(protocol)方法只有一个参数时,根据该单个参数的类型(直接或任意)找到实现。当协议(p
我想从我的 PHP 代码中调用 JavaScript 函数。我通过使用以下方法实现了这一点: echo ' drawChart($id); '; 这工作正常,但我想从我的 PHP 代码中获取数据,我使
这个问题已经有答案了: Event binding on dynamically created elements? (23 个回答) 已关闭 5 年前。 我有一个动态表单,我想在其中附加一些其他 h
我正在尝试找到一种解决方案,以在 componentDidMount 中的映射项上使用 setState。 我正在使用 GraphQL连同 Gatsby返回许多 data 项目,但要求在特定的 pat
我在 ScrollView 中有一个 View 。只要用户按住该 View ,我想每 80 毫秒调用一次方法。这是我已经实现的: final Runnable vibrate = new Runnab
我用 jni 开发了一个 android 应用程序。我在 GetStringUTFChars 的 dvmDecodeIndirectRef 中得到了一个 dvmabort。我只中止了一次。 为什么会这
当我到达我的 Activity 时,我调用 FragmentPagerAdapter 来处理我的不同选项卡。在我的一个选项卡中,我想显示一个 RecyclerView,但他从未出现过,有了断点,我看到
当我按下 Activity 中的按钮时,会弹出一个 DialogFragment。在对话框 fragment 中,有一个看起来像普通 ListView 的 RecyclerView。 我想要的行为是当
我是一名优秀的程序员,十分优秀!