从帮助程序异步返回值

Return value from helper asynchronously?

本文关键字:返回值 异步 帮助程序      更新时间:2023-09-26

getCurrentPosition() 是异步的,那么如何从帮助程序返回值呢?

Template.pos.helpers({
    'nearestLocation': function() {
        var location = undefined;
        if('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(function(position) {
                location = Locations.findOne({
                    geolocation: {
                        $near: {
                            $geometry: {
                                type: 'Point',
                                coordinates:[153.0415850, -27.4477160]
                            }, 
                            $maxDistance: 500
                        }
                    }
                });
                console.log(location.name);
                return location.name;
            });
        }
    }
});

查找工作正常,因为控制台确实输出了正确的结果。我是否错过了一些关于流星工作方式的我应该知道的东西?

只需使用 Session 变量或其他反应式数据源,在找到位置时强制帮助程序重新运行:

Template.pos.helpers({
  nearestLocation: function() {
    var position = Session.get('position');
    // only bother doing the find if the position is set
    if (position) {
      // use position in the find
      var location = Locations.findOne(...);
      return location.name;
    }
  }
});
Template.post.rendered = function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      // set the session variable when/if position is found
      Session.set('position', position);
    });
  }
};
如果值

是异步检索的,则不能直接从函数返回值。 该函数在检索异步值之前返回 U。

解决此问题的常用方法是将回调传递到函数中,然后主机函数调用回调并在检索值时向其传递值。

如果在您使用的基础架构中,nearestLocation函数需要同步(例如,它不能使用回调或返回稍后返回值的承诺),那么您就有点不走运了,因为您无法从 Javascript 中的同步接口返回异步值。 这是做不到的。

我知道的唯一可能的解决方法是以某种方式预测在需要之前很久就需要什么值,以便您可以异步检索所需的值,将其存储起来,然后在对该值发出同步请求时,可以返回它,因为它之前已被检索。

这需要对将请求的内容有高级了解,并提前有足够的时间在需要之前实际检索它。

比回调模式更好的方法是从函数返回一个 promise 对象,该函数有一个 then() 方法,该方法在解析时被调用,因此您可以将响应的处理程序链接到请求上,如下所示:

getCurrentPosition().then(function(result) {});
承诺

在ES6中是原生的,但是你今天使用它们,你必须使用转译器或专门用于像q这样的承诺的库。