jQuery.Deferred()


wechat
WEB前端开发官方公众号
10年服务3000万前端开发工程师
微信号:webfedev
微信扫一扫关注,每天分享前端干货

jQuery.Deferred( [beforeStart ] )返回: Deferred

描述: 一个工厂函数,这个函数返回一个链式实用对象,用返回对象方法来在回调队列中注册多个回调, 调用回调队列,传递任何同步或异步函数的成功或失败状态。

  • 添加的版本: 1.5jQuery.Deferred( [beforeStart ] )

    • beforeStart
      类型: Function( Deferred deferred )
      一个构造函数返回之前调用的函数。

jQuery.Deferred()工厂函数创建一个新的deferred对象。new 运算是可选的。

jQuery.Deferred方法可以传递一个可选的函数, 这个函数在方法返回之前调用,并且传递新的 deferred(延迟)对象作为 this对象作为第一个参数传递给函数。例如,被调用的函数可以使用 deferred.then()绑定回调。

一个Deferred(延迟)对象开始于pending状态。 任何回调使用deferred.then(), deferred.always(), deferred.done(), 或者 deferred.fail()添加到这个对象都是排队等待执行。调用deferred.resolve() 或者 deferred.resolveWith()转换Deferred(递延)到resolved(解决)的状态,并立即执行设置中任何的doneCallbacks。调用deferred.reject() 或者 deferred.rejectWith()转换Deferred(递延)到rejected(拒绝)的状态,并立即执行设置中任何的failCallbacks。一旦对象已经进入了解决或拒绝状态,它处于该状态。回调仍然可以添加到解决或拒绝Deferred(递延) - 他们会立即执行。

Enhanced Callbacks with jQuery

在JavaScript中很常见,有选择地在函数中接受被调用的回调函数。例如, 到jQuery1.5之前的版本中,异步流程比如jQuery.ajax(),接受回调函数有时候在不久的将来调用Ajax请求成功时,错误,和完成。

jQuery.Deferred() introduces several enhancements to the way callbacks are managed and invoked. In particular, jQuery.Deferred() provides flexible ways to provide multiple callbacks, and these callbacks can be invoked regardless of whether the original callback dispatch has already occurred. jQuery Deferred is based on the CommonJS Promises/A design.

One model for understanding Deferred is to think of it as a chain-aware function wrapper. The deferred.then(), deferred.always(), deferred.done(), and deferred.fail() methods specify the functions to be called and the deferred.resolve(args) or deferred.reject(args) methods "call" the functions with the arguments you supply. Once the Deferred has been resolved or rejected it stays in that state; a second call to deferred.resolve(), for example, is ignored. If more functions are added by deferred.then(), for example, after the Deferred is resolved, they are called immediately with the arguments previously provided.

In most cases where a jQuery API call returns a Deferred or Deferred-compatible object, such as jQuery.ajax() or jQuery.when(), you will only want to use the deferred.then(), deferred.done(), and deferred.fail() methods to add callbacks to the Deferred's queues. The internals of the API call or code that created the Deferred will invoke deferred.resolve() or deferred.reject() on the deferred at some point, causing the appropriate callbacks to run.