0

I am doing a small assignment using Facebook API. One of my GET requests involves me send a request and storing the data for later use. Now, I managed to this while using the same data in the same call, however, this time, I would like to store the data inside a global variable to use it in other GET calls. The code I implemented is this:

var pageDataItemGlobal;
$.getJSON("https://localhost:44326/api/Facebook/GetPageFeed?accessToken=" + response.authResponse.accessToken)
    .done(function (data) {
        $.each(data, function (key, pageDataItem) {
            pageDataItemGlobal = pageDataItem;
            for (i in pageDataItem) {
                console.log(pageDataItem[i].name + ', ' + pageDataItem[i].id) //Shows the values
            }
        });
    });
console.log(pageDataItemGlobal) //shoes undefined

I search online and found that if you assign the value of the global variable to the one inside the .each() function, then you can use it. However, it does not return the values. Instead, it just returns undefined.

What am I doing wrong please? Thanks

John Long
  • 11
  • 3
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – freedomn-m Jun 09 '20 at 11:10
  • `$.getJSON` is *asynchronous* so the `.done` call back occurs after the rest of your function has finished - ie after you try to console.log it. This would also be obvious if you looked at the *order of the console logs* that you already have. – freedomn-m Jun 09 '20 at 11:10
  • Thanks for the reply. I understood why, though I still have no idea how to go around it.. Do you suggest a specific way please? – John Long Jun 09 '20 at 11:14
  • Move the code that uses the returned data into the .done callback. In the code you've provided that would be `console.log(pageDataItemGlobal)` - it might be a call to another function. If you need to use that data generically and don't know when it will be loaded, then you'll need to add a "loaded" flag somewhere and check that. – freedomn-m Jun 09 '20 at 11:23
  • I "fixed" it by using another method. I'm temporarily storing the ID in the session storage and using it like that. Thanks for the replies though! – John Long Jun 09 '20 at 11:29

0 Answers0