down vote
favorite
I am making a project with Meteor and I’m having some issues trying to get data out of mongodb in JavaScript. I have the following in a function:
This function gets called later down in the code but it returns an empty array. If I run this code in my browsers console it returns an array with 2 objects in it, which is correct. This leads me wondering if I can use the .fetch() function from within my code? As if I leave off the .fetch() it returns what looks like the usual giant object. My real problem is I need the data in the form that .fetch() gives it to me in. Is there any way around this or a fix?
I have moved it into a meteor method with some test code to try and get it working. Here is the example code:
Server: Meteor.methods({ getSunday: function(){ return 107; } });
Client: console.log(Meteor.call("getSunday"));
That console code returns undefined, can anyone explain to me why this is?
Asynchronous code always requires a callback (function(result)), which means "Do this task, and then when it’s done, do this with the parameters that it returns.
Yes thanks! I did that right after I replied. That is now showing 107 in the console. Now I’m trying to get it to return 107 but that doesn’t seem to be working now… Not even an error message.
So something like this? Meteor.call("getSunday, function(error, result) { if (error) { console.log("Error: " + error.reason) } else { var sundayTime = result; } });
I basically need sundayTime to equal the 107, which it should now. The problem I’m having is I need to use that variable later on in my code but because it is in that meteor.call function the other function cant see it (Uncaught ReferenceError: sundayTime is not defined)
It’s a common thing that new people run into. Basically, you either need to define sundayTime outside the callback, then set the value inside (if you wish to use it outside the callback), or any code that uses sundayTime needs to be inside the callback, or sundayTime won’t have a value outside that block of code.