0
x = 0;

    T.get('statuses/user_timeline', function(err, data, response) {

        x = data[0].text

    });

console.log(x);

I'm using twit to access Twitter's API in node, and can't figure out how to assign data from the API to public variables. All of the examples on its github page use this format. How can I, for instance, get console.log here to print the latest tweet, instead of 0?

Everything with twit itself is working fine. I'm just having this JS problem.

  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Paul Draper Nov 22 '14 at 09:35
  • Basically, you don't. You have to structure your code to work asynchronously. It's requires a mental shift. – Paul Draper Nov 22 '14 at 09:35

1 Answers1

1

You completely misunderstand the control flow here.

Call to T.get is asynchronous, which means the code

console.log(x);

is executed is most cases before the body of function (since the control is passed to it immediately after async call to T.get was initiated.) The only way to accomplish what you want is to use callback like:

var callback = function(x) {
  console.log(x);
}
T.get('statuses/user_timeline', function(err, data, response) {
    callback(data[0].text);
});

Callback will be called as the request to twitter is completed.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160