fregante / gsap-then

🙏 Make every GSAP Tween a promise. tl.then(doSomething) (GSAP 1 and 2)
https://npm.im/gsap-then
MIT License
29 stars 3 forks source link

Async/await functionality #2

Closed FreddyFY closed 5 years ago

FreddyFY commented 6 years ago

Thanks for this simple plugin.

It would be cool when you can use it with async/await

async () => {
  await TweenLite.to(...);
  console.log('Animation done and image loaded');
}
fregante commented 6 years ago

Hello! I did notice that await doesn't work but I didn't have time to investigate. I'm doing something wrong with the promise but I don't see what it is.

Currently this executes in the correct order, but as you said it stops at await:

https://codepen.io/anon/pen/zJbYZO?editors=0010

If you can figure out how to make it work, please let me know.

FreddyFY commented 6 years ago

This should do the job, for TweenLite.fromTo that also supports .then() I'm not sure how to make the code most effective, for all methods

(function(fromTo) {
  window.com.greensock.TweenLite.fromTo = (
    element,
    duration,
    from,
    to,
    ...rest
  ) => {
    return new Promise(resolve => {
      fromTo(
        element,
        duration,
        from,
        {
          ...to,
          onComplete: () => {
            if (typeof to.onComplete === "function") {
              to.onComplete();
            }
            resolve();
          }
        },
        ...rest
      );
    });
  };
})(window.com.greensock.TweenLite.fromTo);

https://codepen.io/freddyfy/pen/OoqWgz

fregante commented 6 years ago

But then you can’t chain them because it only returns a promise. e.g.

tl.fromTo(...).from(...).then(...)
// fails here  ^

Plus it’s gonna have a lot of overhead if every single tween is a promise

FreddyFY commented 6 years ago

You're right, the whole thing makes likely to much effort for a add-on. Would be cool when gsap supports this.

fregante commented 5 years ago

I don't know what the problem was exactly, but when trying to fix it I realized that await tween resolves with tween, which has a .then property, so await tries to resolve that again, ad infinitum.

I fixed this in v3 by not returning the tween. That part is generally pretty useless because if you can await it or call .then on it, then you also already have access to the tween:

const tl = new TimelineLite();
await tl; // No need for tl = await tl;

// and
tl.then(() => console.log(tl)); // No need for tl.then(tl => console.log(tl))