Using Jquery promise() in 'for' loop to wa

2019-09-15 17:55发布

问题:

I want to know why the following code does not wait for an animation to finish before starting the next animation in the loop.

For some reason all the elements created by the loop are displayed at once and faded in simultaneously. From the code, I would expect that the first element would finish fading in before the first iteration of the loop finishes then the second iteration of the 'for' loop would fade in the next element and so on..

I do not want to use callbacks before this creates messy code and also I want to use a loop which will use dynamic data -- the number of animations will vary.

<div id="container"></div>

<script>
var data = [1,2,3,4]; 

for(var i = 0; i < data.length; i++){
    $("#container").append("<h1>"+data[i]+"</h1>").hide().show("fade",2000);
    $("#container").promise().done(function(){console.log('sweet');});
}
</script>

回答1:

Promises do not magically halt your for loop, all they do is provide a way to chain callbacks. You were doing all your animations at once, and waited for them concurrently to finish. To get them in sequence, you can use

<div id="container"></div>
<script>
[1,2,3,4].reduce(function(prev, d, i) {
    return prev.then(function() {
        console.log('start', i)
        return $("<h1/>", {text: d})
        .appendTo("#container")
        .hide().show("fade",2000) // I assume you meant to animate the h1, not the container
        .promise();
    }).then(function() {
        console.log('sweet! end', i);
    });
}, $.when());
</script>