0

In below code res is a 2 dimensional array contatining .csv data returned by server.

var result;
Meteor.call('parseFile', (err, res) => {
    if (err) {
        alert(err);
    } else {
        // success!
        alert(res[0][0]);
        result = res
    }
});
let longitude = result[0];

I am using above code. And the value stored in result variable is null.However, in alert the variable res has values stored in it. I searched online and they say this is due to some fibre thing and advised to use session variable. But, I am not able to get that correct also. So, my question is basically how to use the array returned by server stored in res variable to use outside the function scope.

Arjun Chaudhary
  • 2,373
  • 2
  • 19
  • 36

3 Answers3

0

This is a classic Asynchronous Call issue. See: How do I return the response from an asynchronous call?

The usual way is to place whatever instructions that depend on your async task result (like let longitude = result[0]) inside that task's callback.

Within Meteor client code, you can also write your instructions in a reactive scope (e.g. within a Blaze helper, or using Tracker.autorun() / Blaze template this.autorun(), using a Reactive Variable for your result. That way, once it gets set by your Meteor.call(), your reactive scope will re-run, this time using the updated value.

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • I am very new to Meteor, I don't understand what you are saying.. Could you please tell me what changes I should do into the code. – Arjun Chaudhary Sep 05 '16 at 08:08
  • Try the classic approach first (see the linked post) – ghybs Sep 05 '16 at 08:38
  • I read that its related to ajax and also nowhere its written how to access out of the scope of function. I think you can read this link https://forums.meteor.com/t/how-to-return-value-on-meteor-call-in-client/1277 so that you can get an idea. – Arjun Chaudhary Sep 05 '16 at 08:45
  • However explanation of link is good.. I will try to read the link again if i get something. – Arjun Chaudhary Sep 05 '16 at 08:49
0

You should use reactive variables for this purpose refer here for better insights

khem poudel
  • 587
  • 7
  • 13
0

See the below example on a html file add the below with appropriate changes

<template name="test">
    <!-- Here is where you want your data -->
    <p>{{test}}</p>
</template>

on the js file add the below

Template.test.onCreated(function() {

  this.test= new ReactiveVar();

  Meteor.call('parseFile', (err, res) => {
    if (err) {
      console.error(err);
    } else {
      // Set data into a reactive variable
      this.test.set(res);
    }
  });
});

Template.test.helpers({
  test: function() {
    // Helper will automatically rerun on method res
    return Template.instance().test.get();
  }
});