I have trouble getting a function to execute correctly before template loading

I believe the issue is with the routing, but I may be wrong here.

I have an issue where a function that I call via Iron Router sometimes doesn’t fully finish making necessary computations before the template renders and the page is filled with n/a’s and NaNs (because of the calculations not finishing before the template loads or renders). So what happens is after the user logs in, he/she uploads data via external file. This data is then stystematically added to an existing MongoDB collection then calculations are being made by function computeValues().

My problem, as I’ve stated above, is that there are times where the computeValues() function doesn’t completely finish making necessary calculations, but the template renders anyway. When I refresh this page, the process works as it’s supposed to. It’s only when I’m routed from one page to this particular template/page (called mainPage) when this issue exists. Then, there are other instances where it works like it’s supposed to and the template doesn’t render before the function executes and computers the data completely.

Here is the particular code for the Iron Router:

Router.route("/analyze/main", {name: "main",
subscriptions: function(){
  return Meteor.subscribe("data");
},
onBeforeAction: function(){
  if(! Meteor.user()){
    this.layout("accessDenied");
  } else{
    this.next();
}},
action: function(){
this.wait(computeValues());
if(this.ready()){
  this.layout("mainPage");
} else{
  this.layout("loading");
}
}});

Here is what I added to the template’s onRendered() function:

Template.mainPage.onRendered(function(){
  computeValues();
});

Adding or removing the onRendered part for the template makes no reason. The problems still persist from time to time. I just can’t figure out what’s causing this or how to fix it.

The particular function that does all the calculations, computeValues(), is located in the lib folder due to the need to expedite the loading process and have access to global variables immediately. I can’t post the code because it’s over 3000 lines long. But the extensiveness of this function does not explain why it works 20% of the time when routed, and not working 80% of the time, all while working 100% of the time being on the mainPage template and refreshing for reload.

On refresh, the subscription data need to arrive to client - if u want to help them to be available right away, use fast-render package.

Also why not put the computation to onCreated instead of onRendered if it is not accessing DOM directly, but just manipulate data available in JS ?