promise()
返回一个 Promise 对象,用来观察当某种类型的所有行动绑定到集合,排队与否还是已经完成。
.promise([type ][, target ])
- type(默认:
fx
)类型: String。需要待观察队列类型。 - target类型: PlainObject。将要绑定 promise 方法的对象。
.promise()
方法返回一个动态生成的 Promise,当绑定到集合中的所有特定动作(action)已经被加入或未被加入到队列中时,生成的 Promise 将被受理(resolve)。
默认情况下,type
的值是"fx"
,这意味着返回被受理(resolve)的 Promise 对象的时机,是在所有被选中元素的动画都完成时发生的。
解决上下文和唯一的参数是哪个集合到.promise()
被调用。
如果提供target
参数,.promise()
在该参数上添加方法,然后返回这个对象,而不是创建一个新的。它适用于在一个已经存在的对象上添加 Promise 行为的情况。
注意:返回的 Promise 被链接到延迟对象上,保存在元素的
.data()
中。由于.remove()
方法会移除元素上的 data,同时也会移除元素本身。所以,使用它会防止任何元素上未被受理的(unresolved) Promise 被受理(resolving)。如果有必要在元素的 Promise 被受理(resolved)之前,从 DOM 中移除该元素的话,请使用.detach()
来代替。之后再调用.removeData()
例子
在一个没有激活动画的集合上调用.promise(),返回一个被受理(resolved)的 Promise:
var div = $( "<div />" ); div.promise().done(function ( arg1 ) { // will fire right away and alert "true" alert(this === div && arg1 === div ); });
当所有的动画结果时(包括那些在动画回调函数和之后添加的回调函数中初始化的动画),受理(Resolve)返回的 Promise:
<!DOCTYPE html> <html> <head> <style> div { height: 50px; width: 50px; float: left; margin-right: 10px; display: none; background-color: #090; } </style> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <button>Go</button> <p>Ready...</p> <div></div> <div></div> <div></div> <div></div> <script> $("button").bind( "click",function () { $("p").append( "Started..."); $("div").each(function ( i ) { $(this ).fadeIn().fadeOut( 1000 * (i+1) ); }); $( "div" ).promise().done(function () { $( "p" ).append( " Finished! " ); }); }); </script> </body> </html>
Ready...
使用$.when()语句(.promise()方法使得在 jQuery 集合中实现它变成了可能),受理(Resolve)返回的 Promise:
<!DOCTYPE html> <html> <head> <style> div { height: 50px; width: 50px; float: left; margin-right: 10px; display: none; background-color: #090; } </style> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <button>Go</button> <p>Ready...</p> <div></div> <div></div> <div></div> <div></div> <script>var effect =function () {return $("div").fadeIn(800).delay(1200).fadeOut(); }; $("button").bind( "click",function () { $("p").append( " Started... "); $.when( effect() ).done(function () { $("p").append(" Finished! "); }); }); </script> </body> </html>
Ready...