Get JSON data out of the Scope

Viewed 38

I have this data inside a JSON:

{"minmax":["0.01","67.00"]}

And I want to get it using jQuery, this is what I am doing:

$.getJSON("../../dados/opcoesMinMax.json", function(data) {
    var getMinMax = data;
});

// Need to use data here, out of the scope

I also tried to do it using callback, doing this:

function getMinMax(callback) {
    $.getJSON("../../dados/opcoesMinMax.json", function(data) {
        callback(JSON.stringify(data));
    });
}

// Need to use data here, out of the scope

Even using callback, I cannot recover data. console.log(getMinMax); returns me the function. and console.log(getMinMax()); returns me undefined and says callback is not a function.

1 Answers

The second pattern you use is valid, and will work. The issue is because in your call to getMinMax() you need to provide the callback function as an argument. This is why you're currently seeing the 'callback is not a function' error. Try this:

function getMinMax(callback) {
  $.getJSON("../../dados/opcoesMinMax.json", callback);
}

getMinMax(data => {
  // this is the callback function. Work with the data here...
  console.log(data);
});
Related