Примеры для jQuery .promise()


Using .promise() on a collection with no active animation returns a resolved 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 );
});

Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on):

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-1.10.2.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>

Демонстрация:

Resolve the returned Promise using a $.when() statement (the .promise() method makes it possible to do this with jQuery collections):

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-1.10.2.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>

Демонстрация: