user348173
user348173

Reputation: 9288

wrap code by promises

I use GSAP library for animation. I am trying to wrap it by promises:

$().promise().then(function() {
     var timeline = new TimelineMax();
    timeline.to( $('.box'), 0.5, {css: {boxShadow: '0 0 40px 40px red'}}, 'box' )
            .to($('.box'), 0.5, {css: {boxShadow: 'none'}}, 'box+=5')

})
.then(console.log(1))

But, console.log run at start. How to fix it?
DEMO

Upvotes: 0

Views: 95

Answers (3)

Mohamad Shiralizadeh
Mohamad Shiralizadeh

Reputation: 8765

you should use $.Deferred() for a promise object.

jQuery.Deferred()

A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

More

var dfd = $.Deferred();

var timeline = new TimelineMax();

timeline.to( $('.box'), 0.5, {css: {boxShadow: '0 0 40px 40px red'}}, 'box' )
        .to($('.box'), 0.5, {css: {boxShadow: 'none'}}, 'box+=5');

// When animation ended you should call dfd.resolve()

dfd.done(function() {
    alert("succeeded");
});

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

You need to do something like

var def = $.Deferred(function (def) {
    var timeline = new TimelineMax({
        onComplete: function () {
            //on complete of the animation resolve the promise
            def.resolve();
        }
    });

    //rest of your animation code
})

def.done(function (a) {
    //need to do it in a callback
    console.log(1, a)
})

Demo: Fiddle

Upvotes: 1

fahhem
fahhem

Reputation: 466

You have to pass in a function that does the logging:

$().promise().then(function() {
     var timeline = new TimelineMax();
    timeline.to( $('.box'), 0.5, {css: {boxShadow: '0 0 40px 40px red'}}, 'box' )
            .to($('.box'), 0.5, {css: {boxShadow: 'none'}}, 'box+=5')

})
.then(function(){ console.log(1) })

Upvotes: 1

Related Questions