HTML
<div id="x">x</div>
<div id="y">y</div>
<div id="z">z</div>
CoffeeScript版
最初のコード
CoffeeScript
$('#x').animate
marginLeft: 40
, ->
$('#y').animate
marginLeft: 40
, ->
$('#z').animate
marginLeft: 40
コールバック地獄やめる
CoffeeScript
d = new $.Deferred
$('#x').animate
marginLeft: 40
, -> d.resolve()
d.promise().then ->
$('#y').animate
marginLeft: 40
.then ->
$('#z').animate
marginLeft: 40
reduce(es6)を使う
CoffeeScript
[
->
$('#x').animate
marginLeft: 50
->
$('#y').animate
marginLeft: 50
->
$('#z').animate
marginLeft: 50
].reduce (prev, current, i) ->
prev.then -> current()
, new $.Deferred().resolve()
JavaScript版
最初のコード
JavaScript
$('#x').animate({
marginLeft: 40
}, function() {
$('#y').animate({
marginLeft: 40
}, function() {
$('#z').animate({
marginLeft: 40
});
});
});
コールバック地獄やめる
JavaScript
var d = new $.Deferred;
$('#x').animate({
marginLeft: 40
}, function() {
d.resolve();
});
d.promise().then(function() {
return $('#y').animate({
marginLeft: 40
});
}).then(function() {
return $('#z').animate({
marginLeft: 40
});
});
reduce(es6)を使う
JavaScript
[
function() {
return $('#x').animate({
marginLeft: 50
});
}, function() {
return $('#y').animate({
marginLeft: 50
});
}, function() {
return $('#z').animate({
marginLeft: 50
});
}
].reduce(function(prev, current, i) {
return prev.then(function() {
return current();
});
}, new $.Deferred().resolve());