如何使onBeforeAction调用等到meteor.js中的函数调用完成? [英] How to make onBeforeAction call wait until a function call inside finishes in meteor.js?

查看:77
本文介绍了如何使onBeforeAction调用等到meteor.js中的函数调用完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与meteor.js同步的onBeforeAction方法

I have a synchronized onBeforeAction method with meteor.js

Router.onBeforeAction(function() {
    var self;

    self = this;

    authToken = Session.get('authToken');

   if (!authToken) {
       this.redirect('login');
       this.next();
   } else {
       Meteor.call('validateAuthToken', authToken, function (error, result)) {
           if (result) {
               self.next();
           } else {
               self.redirect('login');
               self.next();
           }
       }
   }
});

我需要通过调用服务器调用来验证存储在Session中的身份验证令牌.但是,当我执行此方法时,它总是会引发异常.而且我发现原因是因为onBeforeAction调用在validateAuthToken调用返回之前被终止了.因此self.next()不会采取任何措施.因此,我想知道如何防止onBeforeAction调用停止直到validateAuthToken返回经过验证的结果然后继续进行?

I need to validate an authentication token stored in Session by invoking a server call. But this method always throws an exception when I am executing it. And I found out the reason is because the onBeforeAction call is terminated before the validateAuthToken call returns. And thus the self.next() won't take action. So I wonder what can I do to prevent the onBeforeAction call from stopping until the validateAuthToken returns the validated result and then proceed?

我通过等待会话变量尝试了不同的实现,但是似乎就绪状态从未设置为true

I've tried a different implementation by wait on a session variable, but it seems the ready state is never set to true

Router.onBeforeAction(function() {
    var authToken;

    authToken = Session.get('authToken');

    if (!authToken) {
        this.redirect('login');
        this.next();
    } else {
        Meteor.call('validateAuthToken', authToken, function (error, result) {
            if (!error) {
                Session.set("tokenValidated", result);
            }
        });

        this.wait(Meteor.subscribe('token', Session.get('tokenValidated')));
        if (this.ready()) {
            if (!Session.get("tokenValidated")) {
                this.redirect('login');
                this.next();
            } else {
                this.next();
            }
        }
    }

});

推荐答案

您还可以使用 https://github.com/iron-meteor/iron-router/issues/426

Ready = new Blaze.ReactiveVar(false);
Router.route('feed',{
  waitOn: function () {
    Meteor.call('getInstagramUserFeed', function(error, result) {
      if(!error) Ready.set(result)
    });
    return [
      function () { return Ready.get(); }
    ];
  },
  action: function () {
    if (this.ready()) this.render('feed')
    else this.render('LoadingMany');
  }
});

这篇关于如何使onBeforeAction调用等到meteor.js中的函数调用完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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