2

I've clearly been writing too much CoffeeScript, as I am now realizing I do not have even a basic understanding of scope in pure JS.

After playing for a while, I cannot figure out the problem with the following--

$(document).ready(function() {
    var myUrl = "http://notimportant.com/"
    var photos = getPhotos(myUrl);
    console.log(photos);                        //undefined
});

function getPhotos(url) {
    var a;
    $.get(url, function(data) {
        a = data["photoset"]["photo"];
        console.log(a);                        //my object
    });
    return a;
}

If I put a console.log(a) statement on the line right below 'var a = data["photoset"]["photo"];' it shows that it properly makes the GET request I'm looking for. But I'm finding it impossible to pass that object back to my main block of code, where I want to manipulate it.

Thanks in advance.

common-nighthawk
  • 657
  • 7
  • 10
  • 1
    `$.get` is asynchronous. The statement `return a;` is returned immediately (which is why you're seeing `undefined` in your console) after your `get` call is made. The second argument in get, `function(data)` is your callback which is executed when the ajax response comes back (with the proper data, which you see in your console). To manipulate the data, you could call a function from your `get` callback. – Jack Feb 01 '15 at 03:42

2 Answers2

0

Its not a matter of scope, its a matter of that you are returning an undefined variable before the $.get defines it. Consider making photos a global, then setting it in the $.get success function instead of setting it to 'a'. Inside the success function, you can then issue calls to other functions that would control displaying/processing the photos.

ryanlutgen
  • 2,951
  • 1
  • 21
  • 31
  • Thank you, Vizkos. This is exactly right. Glad to know I'm not going crazy re: scopes. Appreciate you pointing me in the right direction. – common-nighthawk Feb 01 '15 at 17:40
0

The reason photos is undefined is not because of scopes. Its because $.get is executed asynchronously. $.get() returns jqXHR object instead of an HTTP response.

onSuccess callback should be passed to getPhotos() in order to make it work correctly. Alternatively when().then() construct could be used.

$(document).ready(function() {
    var myUrl = "http://example.com/";
    getPhotos(myUrl, renderCatPhotos);    
});

function getPhotos(url, onSuccess) {
    $.get(url, onSuccess);
}

function renderCatPhotos(data) {
    var a = data.photoset.photo;
    console.log(a);  // a is always available
}

note: you might not even need getPhotos function. You can simply $.get(url, onSuccess); in $(document).ready() instead.

Jay
  • 3,445
  • 2
  • 24
  • 29
  • Thank you for taking the time to write this up, Jev. I noticed the console.log's were printing out in unexpected order. At least glad to know I'm not going crazy re: scopes. Appreciate you taking the time to write this up! – common-nighthawk Feb 01 '15 at 17:42