jQuery Promise执行问题:动画完成后未触发提示框求指导
Hey there! Let's break down what's going wrong with your Promise setup and fix it step by step.
The main issue here is that you're resolving the Promise immediately after starting the animation, not waiting for the animation to finish. Also, your Promise is only created once when the document loads, so the click handler logic doesn't tie into jQuery's animation lifecycle at all.
Fixed Full Code
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="square"></div>
CSS
.square { height: 50px; width: 50px; border: 1px solid; position: absolute; }
JavaScript
$(document).ready(function() { var square = $('.square'); // Wrap the animation logic in a function that returns a Promise function moveLeft() { return new Promise(function(resolve, reject) { square.animate( { left: '200px' }, // Use jQuery's animate complete callback to resolve the Promise function() { resolve(); } ); // Optional: Add reject logic if you need to handle animation failures // For example, if the square is removed mid-animation: // if (!square.length) reject('Square element no longer exists'); }); } // Bind click handler to trigger the animation and its follow-up square.click(function() { moveLeft().then(function() { alertWhenDone(); }); }); function alertWhenDone() { alert('The square has finished!'); }; });
Key Fixes Explained
- Promise tied to animation completion: jQuery's
animate()method accepts a completion callback that runs only when the animation finishes. We callresolve()inside this callback, so the Promise only fulfills once the square has actually stopped moving. - Reusable animation function: By wrapping the animation in a Promise-returning function, every click triggers a fresh animation instance with its own Promise. This avoids the one-time Promise creation issue from your original code.
- Clean separation of concerns: The click handler now only triggers the animation, and the Promise handles waiting for the animation to finish before firing the alert.
内容的提问来源于stack exchange,提问作者Theodore Steiner
相关产品推荐
相关产品推荐

