本文介绍了jQuery 延迟和承诺 - .then() 与 .done()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关 jQuery deferreds 和 promises 的文章,但我看不出使用 .then().done() 用于成功回调.我知道 Eric Hynds 提到了 .done().success() 映射到相同的功能,但我猜 .then() 也是如此,因为所有回调都是在完成一个操作成功.

I've been reading about jQuery deferreds and promises and I can't see the difference between using .then() & .done() for successful callbacks. I know Eric Hynds mentions that .done() and .success() map to the same functionality but I'm guessing so does .then() as all the callbacks are all invoked on a completion of a successful operation.

谁能告诉我正确的用法?

Can anyone please enlighten me to the correct usage?

推荐答案

附加到 done() 的回调将在 deferred 解决时触发.当延迟被拒绝时,将触发附加到 fail() 的回调.

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.

在 jQuery 1.8 之前,then() 只是语法糖:

Prior to jQuery 1.8, then() was just syntactic sugar:

promise.then( doneCallback, failCallback )
// was equivalent to
promise.done( doneCallback ).fail( failCallback )

从 1.8 开始,then()pipe() 的别名并返回一个新的 Promise,参见 此处 了解有关 pipe().

As of 1.8, then() is an alias for pipe() and returns a new promise, see here for more information on pipe().

success()error() 仅在调用 ajax()jqXHR 对象上可用/代码>.它们分别是 done()fail() 的简单别名:

success() and error() are only available on the jqXHR object returned by a call to ajax(). They are simple aliases for done() and fail() respectively:

jqXHR.done === jqXHR.success
jqXHR.fail === jqXHR.error

此外,done() 不限于单个回调,并且会过滤掉非函数(尽管 1.8 版本中存在一个字符串错误,应该在 1.8.1 中修复):

Also, done() is not limited to a single callback and will filter out non-functions (though there is a bug with strings in version 1.8 that should be fixed in 1.8.1):

// this will add fn1 to 7 to the deferred's internal callback list
// (true, 56 and "omg" will be ignored)
promise.done( fn1, fn2, true, [ fn3, [ fn4, 56, fn5 ], "omg", fn6 ], fn7 );

同样适用于 fail().

这篇关于jQuery 延迟和承诺 - .then() 与 .done()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:30