.promise()


.promise( [type ] [, target ] )傳回:Promise

說明:傳回一個 Promise 物件,用於觀察與集合綁定的某種類型的所有動作(無論是否排隊)完成時機。

.promise() 方法會傳回一個動態產生的 Promise,一旦與集合綁定的某種類型的所有動作(無論是否排隊)結束,就會解決這個 Promise。

預設情況下,type"fx",表示在選取元素的所有動畫完成後,傳回的 Promise 會得到解決。

解決內容和唯一參數是已呼叫 .promise() 的集合。

如果提供 target.promise() 會將方法附加到其上,然後傳回此物件,而不是建立新的物件。這對於將 Promise 行為附加到已存在的物件很有用。

注意:傳回的 Promise 會連結到儲存在元素的 .data() 上的 Deferred 物件。由於 .remove() 方法會移除元素的資料以及元素本身,因此會阻止任何元素未解決的 Promise 解決。如果在 Promise 解決之前必須從 DOM 中移除元素,請改用 .detach(),然後在解決後接著使用 .removeData()

範例

在沒有任何主動動畫的集合上使用 .promise() 會傳回已解決的 Promise

1
2
3
4
5
6
var div = $( "<div>" );
div.promise().done(function( arg1 ) {
// Will fire right away and alert "true"
alert( this === div && arg1 === div );
});

在所有動畫結束時解決傳回的 Promise(包括在動畫回呼中啟動或稍後加入的動畫)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>promise demo</title>
<style>
div {
height: 50px;
width: 50px;
float: left;
margin-right: 10px;
display: none;
background-color: #090;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
$( "button" ).on( "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>

示範

使用 $.when() 陳述式解決傳回的 Promise(.promise() 方法讓您可以使用 jQuery 集合執行此操作)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>promise demo</title>
<style>
div {
height: 50px;
width: 50px;
float: left;
margin-right: 10px;
display: none;
background-color: #090;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.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" ).on( "click", function() {
$( "p" ).append( " Started... " );
$.when( effect() ).done(function() {
$( "p" ).append( " Finished! " );
});
});
</script>
</body>
</html>

示範