Catfish
Catfish

Reputation: 19294

$q.when does not work with anonymous function

I'm trying to wrap a synchronous function in a promise.

Can someone please explain the difference between these?

// Does NOT work as expected

var promise = $q.promise;
promise = $q.when(function() {
    return 'foo';
});

promise.then(function(result) {
    console.log('result = ', result); // Prints 'function anonymous()' in chrome console
});

// Works as expected

var promise = $q.promise;
promise = $q.when(getIt());

function getIt() {
    return 'foo';
}

promise.then(function(result) {
    console.log('result = ', result); // Prints 'foo' in chrome console
});

Upvotes: 0

Views: 100

Answers (2)

DRobinson
DRobinson

Reputation: 4471

$q.when isn't intended to execute a function. It's intended to wrap a value that may or may not be a promise.

Imagine a function that fetches data, but has a cache, so if it's cached the value returns immediately, otherwise it returns the $http promise. This may be bad function design, but such functions do exist. Using $q.when allows you to operate on both cases with the same simple code (not have to check if it's a promise or the cached value).

This is particularly useful for dealing with 3rd party libraries that return weird results like that.

As in, you can avoid ugly code and boilerplate that could look like

var results = SomeService.getData(); 
if(results && typeof results.then === "function"){
    results.then(doSomething) 
} 
else { 
    doSomething(results) 
};

Instead, you might get away with something much simpler, along the lines of:

$q.when(SomeService.getData()).then(doSomething);

If the potential result of the function, in this case SomeService.getData, is itself a function, then automatically executing that function would not be the expected behaviour, hence $q.when doesn't (and shouldn't) execute the argument that you're passing.

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

The reason it is returning anonymous function is, you are not executing function, you should write self execute that function there that will call your function.

var promise = $q.promise;
promise = $q.when((function() {
    return 'foo';
})());

Upvotes: 2

Related Questions