I'm trying to retrieve my last tweet from Twitter with https://github.com/jdub/node-twitter
I want to declare a variable, change that variable within a function, then use it again outside that function. Is this possible?
I have authenticated and can see my last tweet if I do:
var tweet;
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
console.log(tweet);
});
But I want to separate my code out and do:
var tweet;
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
});
console.log(tweet);
Tweet is still undefined.
Please educate me :-)
You want to be able to console.log immediately but node.js is not synchronous and that's what makes it so powerful and fast. You have to get used to an asynchronous pattern of coding with node.js. The get request is async. Tweet doesn't get assigned until the callback happens.
Console.log executes immediately after the async request is made.
Try: (EDIT- I suggested this and then question was edited to include this code)
twit.get('http://api.twitter.com/1/statuses/user_timeline.json', function(data) {
tweet = data[0].text;
console.log(tweet); // executed after call returns
});
// executes immediately after request is sent
console.log("request sent");
Notice that the second argument to the twit.get call is an anonymous function that will get executed after it has completed the async request.
The output of this should be "request sent" and then the tweet result in that order.