user2422960
user2422960

Reputation: 1526

Promise chaining. Wait for last promise to resolve

I have 2 functions:

    getDocument: function(title){

    var defer = $q.defer();

    $timeout(function(){

        defer.resolve(true);            
        console.log(1);

    },2000);

    return defer.promise;
},

anotherFunc : function(){

    var defer = $q.defer();

    console.log(2);
    defer.resolve(document);

    return defer.promise;

}

and a call:

    when('/entry/:title', {templateUrl: 'partials/views/entry.php', controller: 'entryCtrl',resolve: {

    document: function($q,$route,$log,document){

        var defer = $q.defer();

        document.getDocument()
            .then(document.anotherFunc());               

        return defer.promise;
    }
}}).

Although i have applied a timeout to getDocument(), anotherFunc() get's called, even when the promise has not been resolved yet.

Why is this?

How can i avoid this behaviour?

Upvotes: 0

Views: 2451

Answers (1)

Bergi
Bergi

Reputation: 665536

anotherFunc() get's called, even when the promise has not been resolved yet.

Because you have called it:

… document.anotherFunc() …
                      ^^

Instead, you want to pass a function into then() that will get called when the promise resolves:

….then(document.anotherFunc)

// or, more explicit and preserving 'this':
….then(function(promiseResult) {
    document.anotherFunc();
})

Upvotes: 4

Related Questions