Home>Article>Web Front-end> What is jquery deferred object

What is jquery deferred object

青灯夜游
青灯夜游 Original
2022-11-02 17:58:04 1975browse

The jquery deferred object is "Deferred", which is a linkable utility object created by calling the jQuery.Deferred() method. A deferred object is chainable, similar to the way a jQuery object is chainable, except that it has its own methods; it can register multiple callback functions to a callback list, call the callback list and pass the success or failure of an asynchronous or synchronous function state.

What is jquery deferred object

The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.

Introduced in jQuery 1.5, Deferred objects are linkable utility objects created by calling the jQuery.Deferred() method. It can register multiple callback functions to the callback list, call the callback list and pass the success or failure status of asynchronous or synchronous functions.

A deferred object is chainable, similar to the way a jQuery object is chainable, except that it has its own methods. After creating a Deferred object, you can use any of the following methods to link directly to the object that was created or saved by calling one or more of its methods.

List

Description

$.Deferred()

$.Deferred() is a constructor, used To return a chained utility object method to register multiple callbacks and call the callback queue, passing the success or failure status of any synchronous or asynchronous functions.

Tips:

    ##$.Deferred() constructor creates a new Deferred (deferred) object, jQuery.Deferred
  • can pass a deferred The selected function is called before the constructor returns and is passed a new Deferred object as the first parameter of the function. For example the called function can use deferred.then() to attach a callback function.
  • A Deferred object starts in the pending state. Any callback functions added to this object using deferred.then(), deferred.always(),
  • deferred.done(), or deferred.fail() are queued for execution.

doneCallbacks immediately after transitioning the delay to the resolved state.
Executes the set failCallbacks immediately after calling deferred.reject() or deferred.rejectWith() to convert the delay into a reject state. Once an object has entered the resolved or rejected state, it remains in that state. Callbacks can still be added to resolved or rejected Deferred objects - they are executed immediately.

    $.Deferred( [beforeStart ] )

Parameter description

Used to determine the Deferred Whether the object has been rejected deferred.notify() Used to pass parameters to the ongoing callback ##deferred .notifyWith() deferred.reject() deferred.rejectWith() deferred.resolve() deferred.resolveWith( ) deferred.state() ##deferred.pipe() deferred.then() is used to call the add handler when the Deferred object is resolved, rejected, or is still in progress. deferred.catch() is used to call the added handler when the Deferred object is rejected. deferred.promise() Used to return the Deferred (deferred) Promise object .promise() Used to return a Promise object and observe whether all actions of a certain type bound to the collection have been added to the queue. Call deferred.resolve() or eferred.resolveWith() to execute the setSyntax##jQuery1.5 added this function
Function Description
$.Deferred() is used to return a chained utility object method to register multiple callbacks, and call the callback queue to pass the success or failure status of any synchronous or asynchronous function.
deferred.always() Used to call the added handler when the Deferred object is accepted or rejected
deferred.done() Used to call the added handler when the Deferred (deferred) object is accepted
deferred.fail() Used to call the added handler when the Deferred (deferred) object is rejected
deferred.progress() Used when the Deferred (Deferred) When the object generates a progress notification, call the add handler
deferred.isRejected()1.8- Used to determine whether the Deferred object has been rejected
##deferred.isResolved()1.8-
is used to pass parameters and the context object to the ongoing callback
is used to reject the delayed object , and pass parameters to the failure callback function
is used to reject the delay object, and pass parameters and context objects to the failure callback function
is used to resolve the deferred object and pass parameters to the doneCallbacks callback function
is used to resolve the deferred object and pass parameters and context objects to doneCallbacks callback function
is used to determine The current state of a Deferred object
Used to filter the state or the deferred object returned by the function The value
Parameter beforeStart Function type Return value
Description
A function called before the constructor returns

jQuery.Deferred() factory function creation A new deferred object.


deferred.always()When the Deferred (deferred) object is accepted or rejected, call through deferred.always () added handler.

Tip: The parameter can be a function or an array of functions. Since deferred.always() returns a Deferred object, it can be connected to other deferred object methods (

Here refers to methods that can continue to call Deferred objects

), including additional .always methods. When a Deferred object is resolved or rejected, callback functions added via deferred.always() are executed in the order in which they were added, and can be passed as arguments to the following methods: resolve , reject , resolveWith or rejectWith .Syntax

deferred.always( alwaysCallbacks [, alwaysCallbacks ] )
  • ##jQuery1.6 added this function

Parameter description

Parameter Description alwaysCallbacks A function or array of functions that is called when the Deferred object is resolved or rejected Note: The deferred.always() method receives the parameters used by .resolve() or .reject() of the Deferred object, which are often very different. For this reason, it is best to just use its behavior without checking its parameters. In most cases, use explicit .done() or .fail() handlers because their parameters are known.
Optional/Function type
Return value

deferred.always() returns a Deferred (deferred) object

Example & Description

jQuery.get() method returns a value from a Deferred (deferred) object of the jqXHR object, we can attach a success and error callback using the deferred.always () method, jQuery sample code:

$.get( "test.php" ).always(function() { alert( "带有成功和错误的回调参数的$.get方法已完成。" ); })


deferred .done()When the Deferred (deferred) object is accepted, the handler added bythe delayed object function deferred.done()

is called.

Tips: This method accepts one or more parameters. deferred.done() returns a Deferred object that can be connected to other deferred object methods (continue to call the methods of the Deferred object), including additional .done() methods. When the Deferred object is resolved, the callback functions added through deferred.done() are executed in the order in which they were added, and can be passed as parameters to the following methods: resolve, resolveWith.

Syntax

deferred.done( doneCallbacks [, doneCallbacks ] )

  • jQuery1.5 added this function

Parameter description

返回值

deferred.done() 返回的是一个Deferred 对象

示例&说明

HTML示例代码:

 

Ready...

jQuery示例代码

function fn1() { $("p").append(" 1 "); } function fn2() { $("p").append(" 2 "); } function fn3(n) { $("p").append(n + " 3 " + n); } var dfd = $.Deferred();//创建一个延迟对象 //添加dfd被解决时需要的被调用的处理函数 dfd .done( [fn1, fn2], fn3, [fn2, fn1] )// 连接一个函数或者函数数组 .done(function(n) {//可以连接其他的方法 $("p").append(n + " we're done."); }); //当点击按钮时修改延迟对象的状态为已解决 //此时调用通过deferred.done()添加的延迟对象被受理后的处理函数 $("button").bind("click", function() { dfd.resolve("and");//输出:1 2 and 3 and 2 1 and we're done. });

deferred.fail()

当 Deferred (延迟)对象被拒绝时,调用通过deferred.fail()添加的处理程序。

提示:该方法接受一个或者多个参数。 deferred.fail() 返回的是一个 Deferred 对象, 可以连接其他的延迟对象方法(继续调用其他Deferred 对象的方法),包括额外的 .fail() 方法。当 Deferred 对象被拒绝时,通过deferred.fail()添加的回调函数 按它们被添加时的顺序执行,并且可以作为参数传递给如下的方法使用:deferred.resolve() 或 deferred.rejectWith()。

语法

  • deferred.fail( failCallbacks [, failCallbacks ] )

jQuery1.5新增该函数

参数说明

Parameter Description doneCallbacks A function or array of functions that is called when the Deferred object is resolved
Optional/Function type
参数 说明
failCallbacks 可选/Function类型一个函数或者函数数组,当Deferred(延迟)对象被拒绝时被调用

返回值

deferred.fail() 返回的是一个Deferred 对象

示例&说明

jQuery示例代码

$(function () { $.get("test.php") .done(function(){ alert("$.get 成功!"); })//解决时调用 .fail(function(){ alert("$.get 失败!"); });//被拒绝时调用 })

deferred.progress()

deferred.progress() 函数当Deferred(延迟)对象生成进度通知时,调用添加处理程序。

注意:当通过调用 notify 或 notifyWith 使延迟对象产生进度通知时,progressCallbacks 就会被调用。 由于 deferred.progress()返回的是延迟对象,所以其它延迟对象方法可以链接到该对象上(链式调用)。当延迟对象被 resolved 或 rejected 时, 进度回调函数将不再被调用,但是当Deferred (延迟)进入resolved(解决) 或 rejected(拒绝)状态后,新添加任何的progressCallbacks将立即执行,使用的参数被传递给.notify() 或 notifyWith()调用

语法

  • deferred.progress( progressCallbacks[,progressCallbacks] )

jQuery 1.7 新增该函数

参数说明

参数 说明
progressCallbacks 可选/Function类型一个函数或者函数数组,当Deferred(延迟)对象生成正在执行中的进度通知时被调用。

Return value

deferred.progress() returns aDeferred object


##deferred.isRejected( )

deferred.isRejected() function is used to determine whether the Deferred object has been rejected.

Deprecated as of jQuery 1.7, please use deferred.state() instead.

Note:

    Returns true if the Deferred object is in the rejected state. This means that deferred.reject() or deferred.rejectWith() has been called on the object, and failCallbacks has been called (or is in the process of being called).
  • Deferred (deferred) objects can have three states: pending (pending), resolved (resolved), or rejected (rejected); use deferred.isResolved() to determine whether the deferred object is in the resolved state.
Syntax

    deferred.isRejected()
This function was added in jQuery 1.5, obsolete in 1.7, and removed in 1.8

Return value

deferred.isRejected() returns a

Boolean type


deferred.isResolved()

deferred.isResolved() function is used to determine whether the Deferred object has been resolved.

Deprecated as of jQuery 1.7, please use deferred.state() instead.

Note:

    Returns true if the Deferred object is in a resolved state. This means that deferred.resolve() or deferred.resolveWith() has been called on the object, and doneCallbacks has been called (or is in the process of being called).
  • Deferred (deferred) objects can have three states: pending (pending), resolved (resolved), or rejected (rejected); use deferred.isRejected() to determine whether the deferred object is in the rejected state.
Syntax

    deferred.isResolved()
This function was added in jQuery 1.5, obsolete in 1.7, and removed in 1.8

Return value

deferred.isResolved() returns a

Boolean type


deferred.notify()

deferred.notify() function is used to set a parameter and pass it to the callback function (progressCallbacks) on the delay object being called.

Note:

    Normally, only the creator of the deferred object (Deferred) can call this method.
  • You can prevent other code from changing the state of the deferred object or reporting its state by calling deferred.promise() to return a restricted Promise object.
  • When deferred.notify is accessed, any progressCallbacks can be added by accessing deferred.then or deferred.progress. Callbacks are executed in the order they were added.

Pass parameters from .notify() to the callback function on the calling delay object, and then call any after the delay object has beenresolved or rejected. notify() (or add progressCallbacks) will
be ignored

Syntax

    deferred.notify( args )
jQuery 1.7 Added this function

Parameter description

返回值

deferred.notify() 返回的是一个Deferred 对象

小知识

jQuery提供的deferred.promise()方法的作用是,在原来的Deferred 对象上返回另一个 Deferred 对象,即受限制的 Promise 对象,受限制的 Promise 对象只开放与改变执行状态无关的方法(比如done()方法和fail()方法),屏蔽与改变执行状态有关的方法(比如resolve()方法和reject()方法),从而使得执行状态不能被改变。

首先看一个 Deferred对象的执行状态被改变的例子:

var dtd = $.Deferred(); // 新建一个Deferred对象 var wait = function(dtd){ var tasks = function(){ alert("执行完毕!"); dtd.resolve(); // 改变Deferred对象的执行状态 }; setTimeout(tasks,5000); return dtd; }; $.when(wait(dtd)) .done(function(){ alert("等待执行!"); }) .fail(function(){ alert("出错啦!"); }); //代码的尾部加了一行dtd.resolve(),这就改变了dtd对象的执行状态,因此导致done()方法立刻执行 dtd.resolve();// 改变Deferred对象的执行状态

再看一个 Deferred对象返回deferred.promise()的例子:

var wait = function(){ var dtd = $.Deferred(); //在函数内部,新建一个Deferred对象 var tasks = function(){ alert("执行完毕!"); dtd.resolve(); // 改变Deferred对象的执行状态 }; setTimeout(tasks,5000); return dtd.promise(); // 返回promise对象 }; $.when(wait()) .done(function(){ alert("哈哈,成功了!"); }) .fail(function(){ alert("出错啦!"); });

wait()函数返回的是promise对象。dtd.promise().resolve()方法不存在,因此无法改变状态,然后,我们把回调函数绑定在这个对象上面,而不是原来的deferred对象上面。

这样的好处是,无法改变promise对象的执行状态,要想改变执行状态,只能操作原来的deferred对象。


deferred.notifyWith()

deferred.notifyWith() 函数用于给定上下文和参数,传递给正在调用的延迟对象上进行的回调函数( progressCallbacks )。

注意:

  • 通常,只有延迟对象(Deferred)的创建者才能调用此方法。
  • 你可以通过调用 deferred.promise() 返回一个受限的 Promise 对象,来阻止其它代码改变延迟对象的状态或报告它的状态。
  • 当 deferred.notifyWith 被调用时, 任何 progressCallbacks 可以通过访问 deferred.then 或者 deferred.progress 来添加。回调 依照他们添加时的顺序执行。

通过 .notifyWith() 传递参数给每个回调函数,当迟延对象已经被 resolved 或被
rejected 之后,再调用任何 .notifyWith() (或者添加 progressCallbacks) 都会被忽略。

语法

  • deferred.notifyWith( context [, args ] )

jQuery 1.7 新增该函数

参数说明

##Parameter args Optional/Object type
Description
Pass an optional parameter to the ongoing callback (progressCallbacks)
参数 说明
context Object类型作为this对象,传递给进行中的回调(progressCallbacks)
args Array类型传递一个可选的参数给进行中的回调(progressCallbacks)

返回值

deferred.notifyWith() 返回的是一个Deferred 对象


deferred.reject()

deferred.reject() 函数用于拒绝延迟对象,并根据给定的参数调用任何 failCallbacks 回调函数。

注意:

  • 通常只有延迟对象的创建者才可以调用该方法。你可以通过调用 deferred.promise(),返回一个受限的 Promise 对象,来阻止其它代码改变延迟对象的状态或报告它的状态。
  • 当延迟对象被 rejected 时,任何通过 deferred.then 或 deferred.fail 添加的 failCallbacks,都会被调用。回调函数按它们被添加时的顺序执行。传递给 deferred.reject() 的 args 参数,会传给每个回调函数。当延迟对象进入 rejected 状态后,任何 failCallbacks 被添加时,就会被立刻执行,并带上传入给 .reject() 的参数。

语法

  • deferred.reject( args )

jQuery1.5新增该函数

参数说明

参数 说明
args Object类型传递一个可选的参数给失败的回调(failCallbacks)

Return value

deferred.reject() returns aDeferred object


deferred.rejectWith( )

deferred.rejectWith() function is used to reject the deferred object and call any failCallbacks callback function based on the given context and args parameters.

Note:

  • Usually only the creator of the deferred object can call this method. You can prevent other code from changing the state of the deferred object or reporting its state by calling deferred.promise(), which returns a restricted Promise object.
  • When the deferred object is rejected, any failCallbacks added through deferred.then or deferred.fail will be called. Callback functions are executed in the order in which they are added. The args parameters passed to deferred.reject() will be passed to each callback function. When the deferred object enters the rejected state, any failCallbacks added will be executed immediately with the parameters passed to .reject().

Syntax

  • deferred.rejectWith( context [, args ] )
##jQuery1.5 added this function

Parameter description

Parameter Description context args
Object typePass an object to failure callbacks (failCallbacks)
Array typePass an optional parameter to the failed callback (failCallbacks)
Return value

deferred.rejectWith() returns a

Deferred object


deferred.resolve()

deferred.resolve() function To resolve the Deferred (delay) object and complete the callback function doneCallbacks according to the given args parameters.

Note:

    Usually only the creator of the deferred object can call this method. You can prevent other code from changing the state of the deferred object or reporting its state by calling deferred.promise(), which returns a restricted Promise object.
  • When the deferred object is resolved, any doneCallbacks added through deferred.then or deferred.done will be called. Callback functions are executed in the order in which they are added. The args parameters passed to deferred.resolve() will be passed to each callback function. When the deferred object enters the resolved state, any doneCallbacks added will be executed immediately with the parameters passed to .resolve().
Syntax

    deferred.resolve( args )
jQuery1.5 added this function

Parameter description

Parameter Description args
Object typePass an optional parameter to the completion callback function (doneCallbacks)
Return value

deferred.resolve () returns a

Deferred object


##deferred.resolveWith()# The ##deferred.resolveWith() function is used to resolve the Deferred (deferred) object and complete the callback function doneCallbacks based on the given context and args parameters.

Note:

Usually only the creator of the deferred object can call this method. You can prevent other code from changing the state of the deferred object or reporting its state by calling deferred.promise(), which returns a restricted Promise object.

    When the deferred object is resolved, any doneCallbacks added through deferred.then or deferred.done will be called. Callback functions are executed in the order in which they are added. The args parameters passed to deferred.resolve() will be passed to each callback function. When the deferred object enters the resolved state, any doneCallbacks added will be executed immediately with the parameters passed to .resolve().
  • Syntax

deferred.resolveWith( context [, args ] )

  • jQuery1.5 added this function

Parameter description

Return value

deferred.resolveWith() returns aDeferred object


deferred.state( )

deferred.state() function is used to determine the current state of a Deferred object.

Mainly used for debugging, for example, before preparing to reject a deferred object, determine whether it is already in the resolved state.

Note:
The deferred.state() method returns a string representing the current state of the Deferred object. Deferred objects can be in one of three states:

  • "pending": Deferred objects are in an unfinished state.
  • "resolved" : The Deferred object is in the resolved state, which means that the object's deferred.resolve() or
    deferred.resolveWith() has been called and doneCallbacks has been called (or in the process of being called)
  • "rejected" : The Deferred object is in a rejected state, which means that the object's deferred.reject() or
    deferred. rejectWith() has been called and failCallbacks has been called (or is in the process of being called).

Syntax

  • deferred.state()

jQuery1.7 added this function

Return value

deferred.state() returns aString type


deferred.pipe()

#deferred.pipe() function is a utility method for filtering and/or chaining deferred objects.

Note:Starting from jQuery 1.8, the deferred.pipe() method is obsolete. Use deferred.then() instead.

As of jQuery 1.8, the deferred.pipe() method is obsolete. deferred.then() should be used instead.

The deferred.pipe() method returns a new Promise object,is used to filter the status or the value of the deferred object returned by the function, and is passed to the corresponding Promise object The done() and fail() methods
doneFilter and failFilter functions filter the status and value of the original deferred (deferred) resolution/rejection.
Starting from jQuery 1.7, this method also accepts a progressFilter function to filter any notify or notifyWith methods that access the deferred (deferred).

These filters can return a new value when the done() or fail() callback function of the promise object returned by pipe() is called, or return other visible objects (Deferred, Promise, etc.) , these visible objectspasstheir own resolve/rejectstatusand thereturn valuepassed to the pipe promise callback function.

If null is used as the filter function, or no filter function is specified, the same value will be used as the original value when the pipe promise is accepted (resolve) or rejected (reject).

Syntax

  • deferred.pipe( [doneFilter ] [, failFilter ] )
## This function was added in jQuery 1.6 and is obsolete in 1.8

    deferred.pipe( [doneFilter ] [, failFilter ] [, progressFilter ] )
This function was added in jQuery 1.7 and is obsolete in 1.8

Parameter Description context Pass the context object to the completion callback function (doneCallbacks) args Pass an optional parameter to the completion callback function (doneCallbacks) Parameter description
Object type
Array type

返回值

deferred.pipe() 返回的是一个* Promise对象*

示例&说明

过滤解决值:

var defer = $.Deferred(), filtered = defer.pipe(function( value ) {//当延迟对象解决时被调用 // 传递给 pipe promise 回调函数的返回的值为10 return value * 2; }); defer.resolve( 5 );//延迟对象被解决 调用pipe() return 10 filtered.done(function( value ) {//filtered 传递之前返回的值 10 alert( "值是(2*5 =) 10: " + value );//弹出框输出:值是(2*5 =) 10:10 });

过滤拒绝值:

var defer = $.Deferred(), //延迟得到解决时调用回调函数为null //延迟得到拒绝的回调函数传递值value * 3 给Promise对象filtered 的fail的回调函数 filtered = defer.pipe( null, function( value ) { return value * 3; }); defer.reject( 6 );//延迟对象被拒绝 调用pipe() return 18 filtered.fail(function( value ) { alert( "值是(3*6=)18:" + value );//弹出框输出:值是(3*6 =) 18:18 });

链任务(?)

var request = $.ajax( url, { dataType: "json" } ), chained = request.pipe(function( data ) { //request返回值给url2 return $.ajax( url2, { data: { user: data.userId } } ); }); chained.done(function( data ) { // 通过第一个请求取回data值提供给URL2 });

deferred.then()

deferred.then() 函数当Deferred(延迟)对象被解决/拒绝或仍在进行中时,调用添加处理程序。

注意:

  • 如果没有这种类型的回调是需要的,参数可以为 null 。或者使用.done(),.fail()或者 .progress()设置只有一种未经过滤的状态或值的回调类型。
  • 从jQuery 1.8开始, 方法返回一个新的 promise ,可以通过一个函数过滤延迟对象的状态和值,用来替换现在过时的deferred.pipe() 方法。
  • 回调是依照他们被添加时的顺序执行的,由于 deferred.then 返回 Promise 对象,可以链接其它的 Promise 对象,包括附加的 .then() 方法。

doneFilter 和 failFilter函数过滤原延迟对象的解决/拒绝的状态和值。
progressFilter 函数过滤任何调用原有的延迟对象的notify 和 notifyWith的方法。
这些过滤器函数可以返回一个新的值传递给的 Promise 对象的.done() 或 .fail() 回调,或他们可以返回另一个观察的对象(延迟对象,Promise 对象等)传递给它的解决/拒绝的状态和值,Promise 对象的回调。
如果过滤函数是空,或没有指定,promise(承诺)将得到与原来值相同解决(resolved)或拒绝(rejected)。

语法

  • deferred.then( doneFilter [, failFilter ] [, progressFilter ] )

    jQuery1.8新增该函数

  • deferred.then1.8-( doneCallbacks, failCallbacks)

    jQuery1.5新增该函数,1.8移除

  • deferred.then1.8-( doneCallbacks, failCallbacks[, progressFilter ] )

    jQuery1.7新增该函数,1.8移除

参数说明

Parameter Description doneFilter failFilter progressFilter
Function typeOptional function that is called when the delay is resolved
Function TypeOptional function, called when delay is rejected
Function TypeOptional function, called when progress notifications are sent to Deferred(deferred) is called
参数 说明
doneFilter Function类型可选 当Deferred(延迟)对象得到解决时被调用的一个函数
failFilter Function类型可选 当Deferred(延迟)对象得到拒绝时被调用的一个函数
progressFilter Function类型可选 当Deferred(延迟)对象生成进度通知时被调用的一个函数调用
doneCallbacks Function类型当Deferred(延迟)对象得到解决时被调用的一个函数或函数数组
failCallbacks Function类型当Deferred(延迟)对象得到拒绝时被调用的一个函数或函数数组
progressCallbacks Function类型当Deferred(延迟)对象生成进度通知时被调用的一个函数或函数数组

返回值

deferred.then() 返回Promise 对象

示例&说明

HTML代码:

 

过滤解决值:

var filterResolve = function() { var defer = $.Deferred(), //当延迟对象解决时被调用 //过滤解决值给then()的返回Promise对象的完成回调函数 filtered = defer.then(function( value ) { return value * 2; }); defer.resolve( 5 ); //添加Promise对象的完成回调函数 filtered.done(function( value ) { $( "p" ).html( "值是 ( 2*5 = ) 10: " + value ); }); }; $( "button" ).on( "click", filterResolve );

过滤拒绝值:

var defer = $.Deferred(), //延迟得到解决时调用回调函数为null //延迟得到拒绝的,回调函数过滤拒绝值 //传递过滤的拒绝值 value * 3 给then()的返回Promise对象的拒绝回调函数fail filtered = defer.then( null, function( value ) { return value * 3; }); defer.reject( 6 );//延迟对象被拒绝 调用then() return 18 //then()的返回Promise对象添加拒绝回调函数,并获取过滤的拒绝值 filtered.fail(function( value ) { alert( "值是(3*6=)18:" + value );//弹出框输出:值是(3*6 =) 18:18 });

链任务(?)

var request = $.ajax( url, { dataType: "json" } ), chained = request.then(function( data ) { //request返回值给url2 return $.ajax( url2, { data: { user: data.userId } } ); }); chained.done(function( data ) { // 通过第一个请求取回data值提供给URL2 });

deferred.catch()

当Deferred对象被拒绝(reject)时,调用通过deferred.catch()添加的处理程序。

deferred.catch( fn ) 是 deferred.then( null, fn )的一个别名

语法

  • deferred.catch( failCallbacks )

jQuery 3.0 新增该函数

参数说明

参数 说明
failCallbacks Function类型一个函数,当 Deferred 对象被拒绝(reject)时被调用

返回值

deferred.catch() 返回的是一个Promise 对象

示例&说明

jQuery.get 方法返回一个jqXHR对象, 它是从Deferred对象派生的,当Deferred对象被拒绝(reject) 时,我们可以使用.catch方法来处理,jQuery示例代码:

$.get( "test.php" ) .then( function() { alert( "$.get succeeded" ); } ) .catch( function() { alert( "$.get failed!" ); } );

deferred.promise()

deferred.promise() 函数返回 Deferred(延迟)的 Promise 对象。

注意:

  • 方法允许一个异步函数阻止那些干涉其内部请求的进度(progress)或状态(status)的其它代码。

  • Promise 对象只包含 deferred 对象的一组方法,包括:done(),then(),fail(),isResolved(), isRejected(), always(), 这些方法只能观察一个 deferred 的状态;不包括任何用于改变状态的延迟方法(resolve, reject, notify, resolveWith, rejectWith, 和 notifyWith),因此Promise 对象无法更改 deferred 对象的内在状态

  • deferred.promise()也可以接受一个 target 参数,此时传入的 target 将被赋予 Promise 的方法,并作为结果返回,而不是创建一个新对象(这个方法可以用于在已经存在的对象上绑定 Promise 行为的情况)。

语法

  • deferred.promise( [target ] )

jQuery 1.5 新增该函数

参数说明

参数 说明
target Object类型绑定 promise 方法的对象。

返回值

deferred.promise() 返回的是一个Promise 对象

示例&说明

创建一个延迟对象,并设定两个延时时间是随机的定时器,分别用于受理(resolve)和拒绝(reject)延迟对象。无论哪一个先执行,都会调用其中一个回调函数。而另一个定时器则不会产生任何效果,因为在最先调用的那个定时器处理中,延迟对象已经处于完成状态(resolved 或 rejected 状态)。同时,还会设定一个定时器进度(progress)通知函数,用于进度通知处理,并在文档的 “body” 中显示 “working…”,以下为一次测试时的jQuery示例代码:

function asyncEvent(){ var dfd = new jQuery.Deferred(); var resolveValue=400+Math.random()*2000; var resolveTime=Math.floor(resolveValue) console.log("resolveTime"+resolveTime)//resolveTime:1890ms // 在一个随机的时间间隔之后 Resolve (解决状态) setTimeout(function(){ dfd.resolve("欢呼"); }, Math.floor(resolveTime)); var rejectValue=400+Math.random()*2000; var rejectTime=Math.floor(rejectValue) console.log("rejectTime"+rejectTime)//rejectTime:1364ms // 在一个随机的时间间隔之后 reject (拒绝状态) setTimeout(function(){ dfd.reject("对不起"); },rejectTime); // 每半秒显示一个"working..."消息 setTimeout(function working(){ //"pending" : Deferred 对象是尚未完成状态 //0ms 执行一次 500ms执行一次 1000ms执行一次 //1364ms 执行 dfd.reject("对不起") //传递拒绝值"对不起" 给拒绝过滤函数 alert( status+', 这次你失败了' ); if ( dfd.state() === "pending" ) { //向正在执行的Deferred 对象的回调函数列表传递参数 dfd.notify("working... "); setTimeout(working, 500); } }, 1); // 返回 Promise 对象,调用者不能改变延迟对象 return dfd.promise(); } // 为异步函数附加一个done, fail, 和 progress 处理程序 //如果向 jQuery.when 传入一个延迟对象,那么会返回它的 Promise 对象(延迟方法的一个子集) $.when( asyncEvent() ).then( function(status){ alert( status+', 事情进展顺利' ); }, function(status){ alert( status+', 这次你失败了' ); }, function(status){ $("body").append(status); } );

使用目标参数,产生现有对象的Promise对象:

// 现有对象 var obj = { hello: function( name ) { alert( "Hello " + name ); } }, // 创建一个延迟 Deferred defer = $.Deferred(); // 设置对象作为 promise defer.promise( obj ); // Resolve (解决) 该对象 defer.resolve( "John" ); // 使用该对象作为 Promise,向受理列表中添加回调函数 //延迟对象状态为解决,因此done 被调用 obj.done(function( name ) { obj.hello( name ); //将弹出 "Hello John" }).hello( "Karl" ); // 将弹出 "Hello Karl";

.promise()

.promise() 函数返回一个 Promise 对象,观察某种类型被绑定到集合的所有行动,是否已被加入到队列中。

返回的 Promise 被链接到延迟对象上,保存在元素的 .data() 中。由于 .remove() 方法会移除元素上的 data,同时也会移除元素本身。所以,使用它会防止任何元素上未被受理的(unresolved) Promise 被受理(resolving)。如果有必要在元素的 Promise 被受理(resolved)之前,从 DOM 中移除该元素的话,请使用.detach() 来代替。之后再调用 .removeData()

注意:

  • .promise() 方法返回一个动态生成的 Promise,当绑定到集合中的所有特定动作(action)已经被加入或未被加入到队列中时,生成的 Promise 将被受理(resolve)。

语法

  • .promise( [type ] [, target ] )

jQuery 1.5新增

参数说明

参数 说明
type 可选/String类型需要待观察队列类型。
target 可选/PlainObject类型将要绑定 promise 方法的对象。

默认情况下, type的值是”fx” ,这意味着返回被受理(resolve)的 Promise 对象的时机,是在所有被选中元素的动画都完成时发生的。

如果提供target参数,.promise()在该参数上添加方法,然后返回这个对象,而不是创建一个新的。它适用于在一个已经存在的对象上添加 Promise 行为的情况。

返回值

.promise()方法返回一个动态生成的Promise对象

示例&说明

1.在一个没有激活动画的集合上调用 .promise()
相关的jQuery示例代码:

//在一个没有激活动画的集合上调用 .promise(),返回一个被受理(resolved)的 Promise var div = $( "
" ); div.promise().done(function( arg1 ) { //弹出 "true" alert( this === div && arg1 === div ); });

2.当所有的动画结果时(包括那些在动画回调函数和之后添加的回调函数中初始化的动画),受理(Resolve)返回的 Promise,相关HTML代码:

  

准备...

当所有的动画结果时(包括那些在动画回调函数和之后添加的回调函数中初始化的动画),受理(Resolve)返回的 Promise,相关jQuery代码

$( "button" ).on( "click", function() { $( "p" ).append( "已开始..." ); $( "div" ).each(function( i ) { $( this ).fadeIn().fadeOut( 100 * ( i + 51 ) ); }); $( "div" ).promise().done(function() { $( "p" ).append( " 完成! " ); }); }); //效果显示好像是等动画执行完成后才执行done()方法

使用 $.when() 语句(.promise() 方法使得在 jQuery 集合中实现它变成了可能),受理(Resolve)返回的 Promise

var effect = function() { return $("div").fadeIn(800).delay(1200).append(" fadeOut! ").fadeOut(); }; $("button").bind( "click", function() { $("p").append( " 已开始... "); $.when( effect() ).done(function() { $("p").append(" 完成! "); }); //效果显示好像是等动画执行完成后才执行done()方法 });

【推荐学习:jQuery视频教程web前端视频

The above is the detailed content of What is jquery deferred object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn