CodyBugstein
CodyBugstein

Reputation: 23322

Why is the last chained ".then" being evaluated before the function chained before it?

I have a simple $q system set up in Angular.

The controller consists of just:

     var fun1 = function(){
        var deferred = $q.defer();

        $timeout(function(){
            console.log("fun1 resolving...");
            deferred.resolve(5);
        }, 1000);


        return deferred.promise;
    }
    var fun2 = function(){
        var deferred = $q.defer();

        $timeout(function(){
            console.log("fun2 resolving...");
            deferred.resolve(6);
        }, 1000);

        return deferred.promise;
    }
    var promise = fun1().then(fun2()).then(function(data){
        console.log(data);
    });

I'm expecting it to print out:

fun1 resolving....
fun2 resolving....
5

But instead it prints out

fun1 resolving....
5
fun2 resolving....

This seems strange to me. Why is the console.log of the last chained .then() evaluating before actual fun2() itself?

Upvotes: 0

Views: 78

Answers (2)

emanuelbsilva
emanuelbsilva

Reputation: 252

Isn't that because you are calling fun2, instead of just passing it in the then?

Just like:

var promise = fun1().then(fun2).then(function(data){
    console.log(data);
});

But then the result wil be:

fun1 resolving....
fun2 resolving....
6

Instead of outputting 5, because fun2 will pass 6 (deferred.resolve(6);) to your last callback.

Upvotes: 2

Davin Tryon
Davin Tryon

Reputation: 67296

Because you are executing fun2() instead of providing fun2 as a function:

var promise = fun1().then(fun2).then(function(data){
    console.log(data);
});

then expects a function that returns a promise.

Upvotes: 0

Related Questions