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有兩個函數可用於實現函數的異步鏈接:


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拒絕延遲時調用的函數或函數數組。


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
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.