I've been attempting to make this function synchronous. I've read several Stack Overflow posts about Async but I'm unable to comprehend how I would be able to make this synchronous. As of now, it is asynchronous therefore it returns undefined before heading into the callback function.
I call it from the client side:
Meteor.call('screenName',function(error,result) {
if (error) {
console.log(error);
}
else {
window.alert(result);
}
}
And this is the server side method:
Meteor.methods({
'screenName': function() {
T.get('search/tweets',
{
q:'#UCLA',
count:1
},
function(err,data,response) {
var temp = data.statuses[0].user.screen_name;
console.log(temp);
return temp;
}
)
}
});
I'm using the Twitter API and what I want to do is basically retrieve the screen name from the JSON and return it to a variable on the client side. But this is returning undefined because the callback is being compiled after the compiler has reached the end of the 'screenName' function.
I want it to return the value from the callback function but reading up other examples has not helped me comprehend how I can transform my code. I need to make this function synchronous but I don't know how to do it.
This isn't synchronous code, but what I've done to send a server method's result back to a client side function is used serversession to do this. For example:
You can now set a reactiveVariable, or a session, or a template helper to be:
Browser-to-server, it is not possible to call methods synchronously. You're stuck with callback-style code. Synchronous calls are only possible on the server.
http://docs.meteor.com/#/basic/Meteor-call
However, synchronous style code for the server depends if everything else is synchronous. You might want to read the APIs docs if it is possible to write the Twitter API call synchronously. Otherwise, you'll be writing asynchronous code in the end.
@thatgibbyguy answer is the only one that worked for me. I also tried following libraries (maybe they will be useful for somebody):
Simply use
Meteor.wrapAsync
to turn your asynchronousT.get
into a synchronously styled one!It won't actually get executed in a pure "synchronous" way though, it is using a trick known as a Fiber, but you should read the docs to learn more.
Here goes: