简体   繁体   中英

How to make onBeforeAction call wait until a function call inside finishes in meteor.js?

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();
           }
       }
   }
});

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?


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();
            }
        }
    }

});

EDIT : After working with this problem for a little bit I came up with a working example (without the infinite loop). You can use the following code:

Util = {};

// We need to store the dep, ready flag, and data for each call
Util.d_waitOns = {};

// This function returns a handle with a reactive ready function, which
// is what waitOn expects. waitOn will complete when the reactive function
// returns true.
Util.waitOnServer = function(name) {
  // This prevents the waitOnServer call from being called multiple times
  // and the resulting infinite loop.
  if (this.d_waitOns[name] !== undefined &&
      this.d_waitOns[name].ready === true) {
    return;
  }
  else {
    this.d_waitOns[name] = {};
  }
  var self = this;
  // We need to store the dependency and the ready flag.
  this.d_waitOns[name].dep = new Deps.Dependency();
  this.d_waitOns[name].ready = false;

  // Perform the actual async call.
  Meteor.call(name, function(err, or) {
    // The call has complete, so set the ready flag, notify the reactive
    // function that we are ready, and store the data.
    self.d_waitOns[name].ready = true;
    self.d_waitOns[name].dep.changed();
    self.d_waitOns[name].data = (err || or);
  });

  // The reactive handle that we are returning.
  var handle = {
    ready: function() {
      self.d_waitOns[name].dep.depend();
      return self.d_waitOns[name].ready;
    }
  };
  return handle;
}

// Retrieve the data that we stored in the async callback.
Util.getResponse = function(name) {
  return this.d_waitOns[name].data;
}

Which is called from waitOn like so:

Router.route("/test", {
  name: "test",
  action: function() {
    console.log("The data is ", Util.getResponse("testWaitOn"));
  },
  waitOn: function() {
    return Util.waitOnServer("testWaitOn");
  }
})

I wrote a blog post with a more in depth explanation, which you can find here:

http://www.curtismlarson.com/blog/2015/05/04/meteor-ironrouter-waitOn-server/

You can also use this code snippet from 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');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM