How to access variable inside Meteor.call()?


#1

I’d like to access variable inside Meteor.call().

Here, I have numStudys inside Meteor.call(), and console.log() inside Meteor.call correctly shows the value of numStudys (in my case, 4, which is correct), but console.log() outside Meteor.call just keep showing “undefined”.

Is there any ways that I can access numStudys inside Meteor.call, and get the value (in my case, 4)?

export default class StudyPage extends React.Component {
componentDidMount() {
Tracker.autorun(() => {
Meteor.call(‘studys.count’, (error, result) => {
numStudys = result;
console.log("numStudys inside Meteor.call: ", numStudys);
});
console.log("numStudys outside Meteor.call: ", this.numStudys);
});
}
}

My result
numStudys outside Meteor.call: undefined
numStudys inside Meteor.call: 4


#2

Why do you need to? I think both Meteor call and Tracker autorun are async functions, so you will never get the value outside of the functions with regular vanilla JS. You can store it in the component’s state once you have the value available in the callback (if the value is important to the component’s UI or something similar).


#3

Hi - you can use futures in MeteorMethods function to ensure the client “waits” until the “result” is returned to it from the Meteor.call(). That is, the client will just wait for the result to be returned before continuing, using futures. An example could be something like this:

/* In MeteorMethods.jsx on the Server */

import Future from ‘fibers/future’ ;
import { Meteor } from ‘meteor/meteor’ ;

Meteor.methods({

studysCount: function() {

let future = new Future() ;

let STUDYSCOUNT = null ;
STUDIESCOUNT = Studies.count() ;
future.return( STUDIESCOUNT ) ;

return future.wait() ;

}

Google meteor futures and meteor to get more info.