Theodore Steiner
Theodore Steiner

Reputation: 1615

Executing jQuery Promise

I'm trying to wrap my head around the jQuery promise function, but I think I'm missing a step.

I've created a simple example where, onclick, the square moves to the left. What is supposed to happen is when the square has completed it's shift, an alert fires, but I don't think my syntax is correct. Below is my code, can anyone point me in the right direction?

$(document).ready(function() {
  var square = $('.square');

  let moveLeft = new Promise(function(resolve, reject) {
    square.click(function() {
      square.animate({
        left: '200px'
      });
      let functionComplete = true;

      if (functionComplete == true) {
        resolve();
      } else {
        reject();
      }
    });
  });

  moveLeft.then(function() {
    alertWhenDone();
  });

  function alertWhenDone() {
    alert('The square has finished!');
  };
});
.square {
  height: 50px;
  width: 50px;
  border: 1px solid;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>

Upvotes: 0

Views: 88

Answers (3)

bsinky
bsinky

Reputation: 535

JQuery's animate doesn't block execution during the animation, it queues the animation immediately and execution continues. So, in your case let functionComplete = true; wouldn't happen when the animation visually completed, it would be executed immediately after the animation is queued.

What you can make use of here is the complete argument to animate, as seen in the documentation here animate can take an options argument that accepts a complete function to use as a callback.

So, the updated code snippet might look something like this:

let moveLeft = new Promise(function(resolve, reject) {
    square.click(function() {
        square.animate({left: '200px'}, { complete: function() { resolve(); } });
    });
}); //end of promise

That code should behave as you expect - the animation will play out and only when it is complete will your Promise's resolve be called.

Edit: Of course, the use of the Promise here is purely artificial for learning how Promise works and can be used. The complete callback could be used without the Promise to achieve the same effect.

Upvotes: 2

Zenoo
Zenoo

Reputation: 12880

You don't need a Promise to do that. You can simply add a callback function to JQuery animate() like so :

$(function() {
  $('.square').click(function() {
    $(this).animate({
      left: '200px'
    },
    //This function will execute after the animation has ended
    function(){
      alert('test');
    });
  });
});
.square {
  height: 50px;
  width: 50px;
  border: 1px solid;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>

Upvotes: 1

Alexander Presber
Alexander Presber

Reputation: 6635

It's Promise (capital), not promise.

Upvotes: -1

Related Questions