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?

Answers


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();
})

Need Your Help

Cannot insert the value NULL into column C# Entity Framework

c# asp.net entity-framework visual-studio-2010

I wrote an application in VS 2010 and after I inserted a new datetime value in the table the following error appears on saving the changes:

How to map JSON object to Spring Object

java json spring spring-mvc

How to map JSON object to Spring Object... I have AJAX, posting a JSON object to my Spring Controller but how do I make Spring turn that JSON into a Object in java