1

I have a scenario where I'm trying to chain together web animations using promises (bluebird).

By web animations I mean element.animate style animations. I've created a generic Animation Promise wrapper like this:

function promiseAnimation(element, keyframes, timing) {
  return new Promise(function(resolve, reject) {
    element.animate(keyframes , timing).onfinish = function(e) {
      resolve();
    }
  });
}

I then pass an element, array and timing object into that function. The animation executes and the promise resolves. The only issue is the end result looks a bit ugly...

promiseAnimation(element, keyframe1, timing1 ).then(function(){
  //isn't this just as bad as callbacks?
  promiseAnimation(element, keyframe2, timing2 ).then(function(){
    alert('lolz');
  });
});

Why ugly? Because it basically looks like callbacks. Chaining together five of these, seems like it'll leave an unreadable block of code--which is counter intuitive to what Promise(s) seem to ...promise.

I guess an alternative would be to return a function, instead of a promise and explicitly execute it, leaving me with something like this:

promiseAnimation(blah,blah)()
  .then(promiseAnimation(blah,blah))

But that also seems less than ideal. What would be the cleanest way to achieve a clean chain of promises, while also ensuring the .then only executes when the animation is finished?

You can see my code here: http://codepen.io/anon/pen/ONbXdx

richie
  • 457
  • 1
  • 6
  • 19
  • what about creating a list of all your `elements, keyframes and timings`? and then looping through that and calling `promiseAnimation()` function, you could wait for a success response before calling the next iteration? – JanR Mar 15 '16 at 03:00
  • See the duplicate on how to solve your initial problem. Once you've got to chaining instead of nesting, you'll notice that your solution with returning a function simplifies it even more (and move it further away from callback style) - yes, that's a good idea! – Bergi Mar 15 '16 at 03:04

0 Answers0