你如何调用外部函数内部异步函数返回后结束运行? [英] How do you call an outer functions return after an inner async function finishes running?

查看:117
本文介绍了你如何调用外部函数内部异步函数返回后结束运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code:

.filter('getUserName', function(User) {
    return function(id) {
       User.get({ _id: id }, function(user) {
           return user.name;
       });
    };
});

我想中间的函数返回 user.name User.get 是异步的,所以我只能从中间函数返回一旦内异步函数完成运行。

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.

我知道2种方式来运行code一旦异步code运行完成后:用成功的回调,或成功的承诺。然而,这两个创造一个内部函数,因此,我的问题 - 我不知道该怎么办好code,它

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


  • 只运行一次异步函数完成和

  • 从中间的函数返回。

推荐答案

这是一个可怕的适合的过滤器,而只是作为一个知识分子的运动,你可以有过滤器返回一些默认的行为(即返回空白),直到数据牵强,一旦获取应用过滤器。这将需要过滤器是 $状态,这是非常浪费的 - 它会在每个周期消化运行

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

这篇关于你如何调用外部函数内部异步函数返回后结束运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆