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.
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.
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- | Used to determine the Deferred Whether the object has been rejected|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Used to pass parameters to the ongoing callback | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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 | deferred.then() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
deferred.catch() | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
deferred.promise() | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
.promise() | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Description | |
---|---|
Function type | A function called before the constructor returns |
deferred.always()<span style="font-size: 18px;"></span>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
Parameter description
Optional/Function type | A function or array of functions that is called when the Deferred object is resolved or rejected
$.get( "test.php" ).always(function() { alert( "带有成功和错误的回调参数的$.get方法已完成。" ); })
deferred .done()<span style="font-size: 18px;"></span>
When the Deferred (deferred) object is accepted, the handler added by the delayed object function deferred.done()
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.
Parameter description
Optional/Function type | A function or array of functions that is called when the Deferred object is resolved
参数 | 说明 |
---|---|
failCallbacks | 可选/Function类型 一个函数或者函数数组,当Deferred(延迟)对象被拒绝时被调用 |
deferred.fail() 返回的是一个 Deferred 对象
jQuery示例代码
$(function () { $.get("test.php") .done(function(){ alert("$.get 成功!"); })//解决时调用 .fail(function(){ alert("$.get 失败!"); });//被拒绝时调用 })
<span style="font-size: 18px;">deferred.progress()</span>
deferred.progress() 函数当Deferred(延迟)对象生成进度通知时,调用添加处理程序。
注意:当通过调用 notify 或 notifyWith 使延迟对象产生进度通知时,progressCallbacks 就会被调用。 由于 deferred.progress()返回的是延迟对象,所以其它延迟对象方法可以链接到该对象上(链式调用)。当延迟对象被 resolved 或 rejected 时, 进度回调函数将不再被调用,但是当Deferred (延迟)进入resolved(解决) 或 rejected(拒绝)状态后,新添加任何的progressCallbacks将立即执行,使用的参数被传递给.notify() 或 notifyWith()调用
jQuery 1.7 新增该函数
参数 | 说明 |
---|---|
progressCallbacks | 可选/Function类型 一个函数或者函数数组,当Deferred(延迟)对象生成正在执行中的进度通知时被调用。 |
deferred.progress() returns a Deferred object
##deferred.isRejected( )<span style="font-size: 18px;"></span>
Deprecated as of jQuery 1.7, please use deferred.state() instead.Note:
This function was added in jQuery 1.5, obsolete in 1.7, and removed in 1.8Return valuedeferred.isRejected() returns a
Boolean type
deferred.isResolved()<span style="font-size: 18px;"></span>
Deprecated as of jQuery 1.7, please use deferred.state() instead.Note:
This function was added in jQuery 1.5, obsolete in 1.7, and removed in 1.8Return valuedeferred.isResolved() returns a
Boolean type
deferred.notify()<span style="font-size: 18px;"></span>
Pass parameters from .notify() to the callback function on the calling delay object, and then call any after the delay object has been resolved or rejected. notify() (or add progressCallbacks) will <br/> be ignored<br/>
jQuery 1.7 Added this functionParameter description
Description | |||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Optional/Object type | Pass an optional parameter to the ongoing callback (progressCallbacks) |
参数 | 说明 |
---|---|
context | Object类型 作为this对象,传递给进行中的回调(progressCallbacks) |
args | Array类型 传递一个可选的参数给进行中的回调(progressCallbacks) |
deferred.notifyWith() 返回的是一个 Deferred 对象
<span style="font-size: 18px;">deferred.reject()</span>
deferred.reject() 函数用于拒绝延迟对象,并根据给定的参数调用任何 failCallbacks 回调函数。
注意:
jQuery1.5新增该函数
参数 | 说明 |
---|---|
args | Object类型 传递一个可选的参数给失败的回调(failCallbacks) |
deferred.reject() returns a Deferred object
<span style="font-size: 18px;">deferred.rejectWith( )</span>
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:
##jQuery1.5 added this functionParameter description
Description | |
---|---|
Object type Pass an object to failure callbacks (failCallbacks) | |
Array type Pass an optional parameter to the failed callback (failCallbacks) |
Deferred object
deferred.resolve()<span style="font-size: 18px;"></span>
jQuery1.5 added this functionParameter description
Description | |
---|---|
Object type Pass an optional parameter to the completion callback function (doneCallbacks) |
Deferred object
##deferred.resolveWith()<span style="font-size: 18px;"></span>
# 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.
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.
Parameter description
Object type | Pass the context object to the completion callback function (doneCallbacks)args | ||||||||||||||||||||||||||||||||||||
Array type | Pass an optional parameter to the completion callback function (doneCallbacks)
Description | |
---|---|
Function type Optional function that is called when the delay is resolved | |
Function Type Optional function, called when delay is rejected | |
Function Type Optional 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代码:
<button>过滤解决值</button> <p></p>
过滤解决值:
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 });
<span style="font-size: 18px;">deferred.catch()</span>
当Deferred对象被拒绝(reject)时,调用通过deferred.catch()添加的处理程序。
deferred.catch( fn ) 是 deferred.then( null, fn )的一个别名
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!" ); } );
<span style="font-size: 18px;">deferred.promise()</span>
deferred.promise() 函数返回 Deferred(延迟)的 Promise 对象。
注意:
方法允许一个异步函数阻止那些干涉其内部请求的进度(progress)或状态(status)的其它代码。
Promise 对象只包含 deferred 对象的一组方法,包括:done(),then(),fail(),isResolved(), isRejected(), always(), 这些方法只能观察一个 deferred 的状态;不包括任何用于改变状态的延迟方法(resolve, reject, notify, resolveWith, rejectWith, 和 notifyWith),因此Promise 对象无法更改 deferred 对象的内在状态
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";
<span style="font-size: 18px;">.promise()</span>
.promise() 函数返回一个 Promise 对象,观察某种类型被绑定到集合的所有行动,是否已被加入到队列中。
返回的 Promise 被链接到延迟对象上,保存在元素的 .data() 中。由于 .remove() 方法会移除元素上的 data,同时也会移除元素本身。所以,使用它会防止任何元素上未被受理的(unresolved) Promise 被受理(resolving)。如果有必要在元素的 Promise 被受理(resolved)之前,从 DOM 中移除该元素的话,请使用.detach() 来代替。之后再调用 .removeData()
注意:
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 />" ); div.promise().done(function( arg1 ) { //弹出 "true" alert( this === div && arg1 === div ); });
2.当所有的动画结果时(包括那些在动画回调函数和之后添加的回调函数中初始化的动画),受理(Resolve)返回的 Promise,相关HTML代码
:
<style type="text/css"> //没有样式不易观察执行效果,因此添加样式设置 div{ height:100px; width:200px; border:2px solid #334455; margin-top:2px; } </style> <button>Go</button> <p>准备...</p> <div></div> <div></div> <div></div> <div></div>
当所有的动画结果时(包括那些在动画回调函数和之后添加的回调函数中初始化的动画),受理(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!