Reputation: 19208
This is my code:
.filter('getUserName', function(User) {
return function(id) {
User.get({ _id: id }, function(user) {
return user.name;
});
};
});
I want the middle function to return user.name
. User.get
is asynchronous, and so I can only return from the middle function once the inner asynchronous function finishes running.
I know 2 ways to run code once the asynchronous code finishes running: using the success callback, or the success promise. However, both of those create an inner function, hence my problem - I don't know how to run code that
Upvotes: 2
Views: 470
Reputation: 49590
This is a terrible fit for a filter, but just as an intellectual exercise, you could have the filter return some default behavior (i.e. return blank) until data is fetched, and once fetched apply the filter. This would necessitate the filter to be $stateful
, which is very wasteful - it will run on every digest cycle.
app.filter("foo", function($timeout){
var cache = {};
function genFoo(input){
$timeout(function(){
cache[input] = input + "foo!";
}, 1000);
}
var filter = function(input){
if (input in cache) return cache[input];
genFoo(input);
return "";
};
filter.$stateful = true;
return filter;
});
DO NOT do this as a filter :)
Upvotes: 1