When should I use jQuery deferred's “then” method and when should I use the “pipe” method?

问题:

jQuery's Deferred has two functions which can be used to implement asynchronous chaining of functions: jQuery的Deferred有两个函数可用于实现函数的异步链接:

then()

deferred.then( doneCallbacks, failCallbacks ) Returns: Deferred

doneCallbacks A function, or array of functions, called when the Deferred is resolved. doneCallbacks解析Deferred时调用的函数或函数数组。
failCallbacks A function, or array of functions, called when the Deferred is rejected. failCallbacks拒绝延迟时调用的函数或函数数组。

pipe()

deferred.pipe( [doneFilter] [, failFilter] ) Returns: Promise

doneFilter An optional function that is called when the Deferred is resolved. doneFilter解析Deferred时调用的可选函数。
failFilter An optional function that is called when the Deferred is rejected. failFilter拒绝Deferred时调用的可选函数。

I know then() has been around a little longer than pipe() so the latter must add some extra benefit, but what the difference precisely is eludes me. 我知道then()已经比pipe()长了一点,所以后者必须增加一些额外的好处,但正是这种差异恰恰是我的意思。 Both take pretty much the same callback parameters though they differ in name and the difference between returning a Deferred and returning a Promise seems slight. 两者都采用了几乎相同的回调参数,尽管它们的名称不同,返回Deferred和返回Promise之间的区别似乎很小。

I've read the official docs over and over but always find them too "dense" to really wrap my head around and searching has found lots of discussion of the one feature or the other but I haven't found anything that really clarifies the different pros and cons of each. 我已经一遍又一遍地阅读官方文档,但总是发现它们太“密集”而无法真正地包围我的搜索已经找到了很多关于这个或另一个特征的讨论,但我没有发现任何真正澄清不同的东西每个人的利弊。

So when is it better to use then and when is it better to use pipe ? 因此,当是它更好地使用then ,当是它更好地使用pipe


Addition 加成

Felix's excellent answer has really helped clarify how these two functions differ. Felix的出色答案确实有助于阐明这两个功能的区别。 But I wonder if there are times when the functionality of then() is preferable to that of pipe() . 但我想知道是否有时候then()的功能优于pipe()

It is apparent that pipe() is more powerful than then() and it seems the former can do anything the latter can do. 很明显, pipe()then()更强大,似乎前者可以做后者可以做的任何事情。 One reason to use then() might be that its name reflects its role as the termination of a chain of functions processing the same data. 使用then()一个原因可能是它的名称反映了它作为处理相同数据的函数链的终止的作用。

But is there a use case that requires then() 's returning the original Deferred that can't be done with pipe() due to it returning a new Promise ? 但是有一个用例需要then()返回原来的Deferred ,由于它返回一个新的Promise而无法用pipe()完成吗?


解决方案:

参考: https://stackoom.com/en/question/eDB9
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章