1

I am trying to run 3 animations, one after the other such that only when the first one has completed does the second start and only after the second has completed the third starts.

I can do this using nested jQuery animation callbacks

    go("one", function () {
        go("two", function () {
            go("three", null);
        });
    });

http://jsfiddle.net/stevenc/m0en7avd/2/

However, I want to be able to do this using jQuery promises/deferred. I've been creating a deferred object and returning its promise. The animation callback now sets the promise to resolved and only at this point was I expecting the "then" to start:

go("one").then(go("two")).then(go("three"));

What happens though is that all animations set off at the same time.

http://jsfiddle.net/stevenc/wsqm6yo1/11/

Can anyone see what I am missing?

steven_c
  • 11
  • 2

1 Answers1

0

You're invoking the functions instead of calling them, your code is like the following with callbacks:

go("one", go("two", go("three")))

Instead, chain the functions:

go("one").then(function(){ return go("two"); }).
          then(function(){ return go("three"); });

As you can see in this fiddle.

Or use bind which returns a function with fixated arguments:

go("one").then(go.bind($, "two")).then(go.bind($, "three"));

As you can see here. Note that you also have the deferred anti pattern in your code - your go function can be simplified to:

function go(id, c) {
    return $("#" + id).animate({
        left: "300px"
    }).promise()
}
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504