How do you call an outer functions return after an

2019-02-26 20:46发布

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

  • Only runs once the asynchronous function finishes and
  • Returns from the middle function.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-26 21:34

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 :)

查看更多
登录 后发表回答