You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 call resolve() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:19:01