5

Possible Duplicate:
JavaScript asynchronous return value / assignment with jQuery

I need a prototype of chart with constructor, so I wrote this:

function Chart(file) {
  var chart = undefined

  $.getJSON(file, function(data) {

    chart = {
      categories: data.keys
      series: [{
          name: 'first',
          data: data.first
        }, {
          name: 'second',
          data: data.second
      }]
    }

  });

  return chart
}

Then I realized, that because of JaavScript's synchronousness it returns undefined. How should I defere the return statement of Chart?

Community
  • 1
  • 1
ciembor
  • 7,189
  • 13
  • 59
  • 100

1 Answers1

6

1.) Specify a callback function

function Chart(file, callback) {
  var chart = undefined

  $.getJSON(file, function(data) {

    chart = {
      categories: data.keys
      series: [{
          name: 'first',
          data: data.first
        }, {
          name: 'niewykopane',
          data: data.first
      }]
    }
    callback(chart);

  });
}

2.) Synchronous request (not recommended!)

You could use $.ajax() and set the async property to false.

Warning: This method is not recommended! It blocks the whole UI, all other JavaScript and timers until the request is finished!

ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • 2
    If you're going to suggest `async:false`, please outline, stress and **bold** the disadvantages of doing so. – Matt Nov 20 '11 at 14:44
  • I hoped that there is a nicer solution than callback, because I'm initializing object like that: `hour_occurrences = new Highcharts.Chart(new Chart(file))`. But thanks, it works:). – ciembor Nov 20 '11 at 14:53