jQuery - Deferreds - Simple
HTML
<button type="button" id="goBtn">Make Requests</button>
<div id="target">hello</div>
CSS
body{
margin: 10px;
}
#target{
padding:10px;
background-color: #4f69b5;
width: 200px;
color:white;
border:solid 2px #4f68b5;
-moz-border-radius: 28px;
-webkit-border-radius: 28px;
border-radius: 10px;
}
JavaScript
var $testElement = $('#target'),
ajax1 = function() {
$testElement.append('<br/> ajax1');
return $.ajax({
type: 'POST',
url: '/echo/json/',
dataType: "json",
data: {
json: JSON.stringify({
msg: 'ajax 3 data'
})
}
})
},
fadeOut = function(data) {
$testElement.append('<br/> fade out');
console.log(data);
return $testElement.animate({
opacity: 0.25,
margin: '+=250'
}, 2000);
},
fadeIn = function(data) {
$testElement.append('<br/> fade in');
return $testElement.animate({
opacity: 1,
margin: '-=250'
}, 2000);
},
ajax2 = function(data) {
$testElement.append('<br/> ajax2');
return $.ajax({
type: 'POST',
url: '/echo/json/',
dataType: "json",
data: {
json: JSON.stringify({
msg: 'ajax 2 sent this data'
})
}
})
},
itsDone = function() {
$testElement.append('<br/>done')
};
$('#goBtn').click(function() {
// what you pass into the when needs to execute to a promise
var prom = ajax1();
// what you pass into pipe needs to be a function definition that will execute to a promise
$.when(prom).pipe(fadeOut).pipe(fadeIn).pipe(fadeOut).pipe(fadeIn).done(ajax2).always(itsDone);
//THIS WORKS TOO!
//$.when(ajax1()).pipe(fadeOut).pipe(fadeIn).pipe(fadeOut).pipe(fadeIn).done(ajax2).always(itsDone);
});