Adam Zerner
Adam Zerner

Reputation: 19208

How do you call an outer functions return after an inner async function finishes running?

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

Answers (1)

New Dev
New Dev

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;

});

Plunker

DO NOT do this as a filter :)

Upvotes: 1

Related Questions