0

I have some JS code that reads a JSON file in and stores the object:

var queryString = (function () {
  var queryString = null;
  $.ajax({
      'async': false,
      'global': false,
      'url': 'scripts/largeJson.json',
      'dataType': "json",
      'success': function (data) {
          queryString = data;
      }
  });
  return queryString;
})(); 
console.log("LargeJson:" + JSON.stringify(queryString));

This works in general, with a small JSON file, I have no problems, and the JSON object is correctly stored in the queryString variable and correctly printed at the last line.

However, when I am using a larger json file (~700 lines), the queryString variable will be null at the last line of this snippet. I should be running this code synchronously due to the async param. What could be going on here? Does this indicate that my larger file is in some way corrupt? I have run it through a few validators with no problems.

lbrendanl
  • 2,626
  • 4
  • 33
  • 54
  • is this a race condition? Perhaps with a longer JSON string, it returns before the value is set. – jaf0 Jun 11 '14 at 15:14
  • My understanding is that the 'async': false param would force this code to run synchronously, and thus no race conditions like that would be possible. – lbrendanl Jun 11 '14 at 15:20
  • Also, I would not call this a duplicate question, as my question is concerned with why one valid json file would work whereas another might fail. The duplicate question marked concerns asynchronous code and a misunderstanding of callbacks. – lbrendanl Jun 11 '14 at 15:22
  • 1
    The answer to the question also states that syncronous AJAX is really bad. And to use it syncronously you should use `return jqXHR.responseText;` – keiv.fly Jun 11 '14 at 15:28
  • keiv's comment is valid. There's no reason to use a callback if you're doing it sync. – jaf0 Jun 12 '14 at 15:16

0 Answers0