0

I have a function that reads integers from a JSON file and returns an array of those numbers. When I print the data, it's all there. However, when I check the length of the array before returning, I get a size of 0. Why?

function readJSON() {
    var arr = [];
    $.getJSON('foo.json', function(obj) {
        for(i = 0; i < obj.length; i++) {
            arr.push(obj[i]['_bar']);
            // Prints: 1 2 3 4 5
            console.log(obj[i]['_bar']);
        }
    });
    // Prints 0
    console.log(arr.length);
    return arr;
}
ChrisD
  • 674
  • 6
  • 15
  • 4
    Duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – maček Aug 10 '15 at 21:17

2 Answers2

1

The function you're passing to getJSON runs asynchronously when the call to the server completes, (almost certainly) not before the return happens.

dtanders
  • 1,835
  • 11
  • 13
1

it should print 0. because it is getjson is async function You can use this

$.ajax({
    url: "myurl",
    async: false,
    success:function(obj) {
            for(i = 0; i < obj.length; i++) {
                 arr.push(obj[i]['_bar']);
                 // Prints: 1 2 3 4 5
                  console.log(obj[i]['_bar']);
            }
})

This will make sync request from the server. (Not continue until it finish the ajax operation request and receive the data)

Alon
  • 2,919
  • 6
  • 27
  • 47