Returned call is undefined?


#1

Ok so i am using a method to make a request and pull some tables from another URL : paste: http://paste.ee/p/b9INi enter image description here

When called the td’s in the table succesfully print to the server console: http://prntscr.com/721i0k

Buuut, when that text is returned from that method to this client code, undefined is printed to the console: paste: http://paste.ee/p/T1e58

Ideas?


#2

It appears as if you are trying to make an asynchronous call to fetch a URL and then return that result from the Meteor method. The problem is that your method puts the request call on the event loop, continues execution and returns before the request call finishes.

I’m not sure how exactly your request function is written, however Meteor does have synchronous http calls on the server so you could use that instead of something that is async and it will behave in the manor you are expecting. See: http://docs.meteor.com/#/full/http


#3

Yea im just using the popular froatsnook:request package. Also, if it returns before the request is finished, why does it print on the server console?


#4

This is the nature of asynchronous code execution. When you call an async function from within another function the outer function makes the call to the async function which adds a callback to the event loop that will be called after the the long running task is executed. It then keeps executing the rest of the code contained within its scope and then returns. Later once the long running code (in this case an http request) is finished executing and has a result, the callback for the async function is then called with the result of the request and in the case of your example code it finds the title of the page and prints it to the server console.

For a bit more information on this topic you can view this youtube video: https://youtu.be/vMfg0xGjcOI?t=11s


#5

As @copleykj said, you can use a synchronous http call to wait for the response to return. You could also use a future to wait for the returned result from the request. Something like:

Future = Meteor.npmRequire('fibers/future')
future = new Future()

request(url, function(err, response, body) {
  text = ...
  future.return(text);

return future.wait();