0

Why is eventFB1 undefined outside of the graph.get callback function?

And why is the eventFB object different to response I get for res (e.g. in the console log as eventFB1) inside of the graph.get callback function?

var graph = require('fbgraph');

var eventFB = graph.get('13216634559578/posts', {limit: 1, access_token: 34ul345kt39884p'},
                function(err, res) {
                    var eventFB1 = res;
                    console.log(eventFB1);
                });

console.log(eventFB1);

Thanks!

KindOfGuy
  • 3,081
  • 5
  • 31
  • 47
  • 1
    it's `undefined` because of async callback. You are getting `res` later then printing `console.log(eventFB1)` outside of the `graph.get` – Yaroslav Tkachenko Jul 28 '16 at 10:16
  • eventFB1 is undefined oustide, because it is defined inside the function. the scope is not global. To be accesed outside, it must be declared as a global variable.Could you please make a codepen with the code? i tried but it says require and graph is not a function. – sandrina-p Jul 28 '16 at 10:16

1 Answers1

2

It is because graph.get is an asynchronous request whereas javascript is a synchronous execution.

Therefore, your code outside the get call executes before you get the response from the request

Rahul Arora
  • 4,503
  • 1
  • 16
  • 24