-1

This is a simple question but I'm stumped.

I have the method:

    twitter.get('statuses/home_timeline', {screen_name: 'foo'}, function(err,item)     {
    console.log(item);
 });

And I want to be able to access the variable item

I have tried this:

    var twitterFeed = twitter.get('statuses/home_timeline', {screen_name: 'foo'}, function(err, item) {
    return item;
 });


console.log("This should be something: ", twitterFeed);

but every time, the output of the console is undefined.

Any tips on how I can access or return the variable item, to outside its scope?

Thanks!

snollygolly
  • 1,858
  • 2
  • 17
  • 31
jimmycouch
  • 108
  • 9

1 Answers1

0

Without knowing much about the library you're using, I'll assume it's a standard AJAX call. Then the function you're giving to twitter.get will almost surely not be called by the time twitter.get has returned. Rather, it will have specified that it would like that function to be called eventually, and you can't predict when that is. It therefore becomes impossible to reliably do any work with item immediately after twitter.get has returned.

You have two options at that point:

Either do the work you want to do with item inside the function.

E.G. (the right way)

var twitterFeed = twitter.get('statuses/home_timeline', {screen_name: 'foo'}, function(err, item) {
    doStuffWithItem(item);
});

or if you want to keep the value around in some namespace, you can do

var item;
var twitterFeed = twitter.get('statuses/home_timeline', {screen_name: 'foo'}, function(err, it) {
    item = it;
});

And then anything in the same scope as var item will be able to access the result. HOWEVER you will never be able to assume that the value has been put in the variable yet, because you cannot predict when the function has been called. However this is a vaguely sane pattern if, e.g. you want to know the last result found by twitter.get or something. You can of course at any time check if item has been populated with

if(item !== undefined){
    doStuffWithItem(item);
}