我从这里得到了一个非常好的答案,将两个建议的方法缝合在一起,但我不知道如何让代码正常工作。
var animals = ['mouse', 'newt', 'shrew', 'grasshopper', 'frog', 'hedgehog'];
$('#s1text1').delay(dur).fadeOut(dur).promise()
.then(function() {
return $('#s1text2').fadeIn(dur).promise();
})
.then(function() {
var p = new $.Deferred().resolve();
return $.each(animals, function(i, animal) {
p = p.then(function() {
return $('.' + animal).fadeIn(defaultDur, function() {
animateAnimalGroup(animal);
}).promise();
});
})
.then(function() {
return $('#s1text2').fadeOut(dur).promise();
})
.then(function() {
return $('#s1text3').fadeIn(dur).promise();
})
.then(function() {
return $('#s1text4').fadeIn(dur).promise();
});
任何帮助/建议将不胜感激。如果有人知道的话,一篇关于这方面的好的教程/文章也会非常有用,我已经读了一些内容,但正在努力理解它。
最佳答案
你不想返回$.each
的结果,你想返回你在循环中累积的p
promise 。另外,它缺少右括号:
.then(function() {
var p = new $.Deferred().resolve();
$.each(animals, function(i, animal) {
p = p.then(function() {
…
});
})
return p;
})
.then(…)
关于javascript - Promise 和延迟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24067235/