0

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 {

  constructor(props) {
    super(props);

  }

  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

Andy Song
  • 1
  • 2
  • 1
    *the next candy shop is two miles away. You ask someone to get you some candy. You want the candy **now**. you get nothing* <- you can't circumvent the asynchronous nature of things – Jonas Wilms Nov 13 '17 at 17:51

1 Answers1

1

Meteor.Call() is a callback.

You can only access the result of a callback within the callback itself. result is scoped to the callback only. You cannot access that data anywhere outside the Meteor.Call()

See: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Pandelis
  • 1,854
  • 13
  • 20