Lukas
Lukas

Reputation: 7734

jQuery deferred and promise not work corectly

I have this code:

var d = $.Deferred();
var promise = d.promise();
//
promise = promise.then(function(){
    var t = new $.Deferred();
    var cont = $('.cont').find('> div');
    requirejs(["transit"], function(){
        cont.transit({opacity: .4});
        //
        setTimeout(function(){
            cont.remove();
            return t.promise();
        }, 500);
    });
});
//
promise.then(function() {
    console.log('test');
});
//
d.resolve();

I wanna to fire up some action after another. But i need to be shure that the first one is finished. So i use promise and deferred methods. Something is not right bc second action starts before defined timeout delay. What is wrong? Can anybody help?

Upvotes: 0

Views: 131

Answers (3)

Mond Wan
Mond Wan

Reputation: 1912

chain does not correctly setup?

The t promise has not been returned to the chain of d.

Modified code

var d = $.Deferred();
var promise = d.promise();
//
promise = promise.then(function(){
    var t = new $.Deferred();
    console.log('1st promise callback');
    //var cont = $('.cont').find('> div');
    setTimeout(function(){
    //requirejs(["transit"], function(){
        //cont.transit({opacity: .4});
        //
        console.log('timeout 1 func');

        setTimeout(function(){
            console.log('timeout 2 func');
            //cont.remove();
            t.resolve(true);
        }, 10);
    },30);

    return t.promise();
});
//
promise.then(function() {
    console.log('test');
});
//
d.resolve();

Output

1st promise callback (index):27
timeout 1 func (index):33
timeout 2 func (index):36
test

fiddle here

Upvotes: 1

specializt
specializt

Reputation: 1911

You are using some Kind of non-Jquery, asynchronous (which is completely unnecessary if you already have jQuery) function- as asynchronous operations run on a separate thread the caller will finish nigh-instantly. If you really want to ensure sequential execution you may simply use a proper jQuery UI method (like animate : http://api.jquery.com/animate/) and add a complete-handler, as documented in the link

Upvotes: 0

ashkufaraz
ashkufaraz

Reputation: 5307

Why not use the $.when

$.when(function).done(function( x ) {
   console.log('test');
 });

Upvotes: 0

Related Questions