1
1
1alexandr2015-06-22 13:25:37
JavaScript
1alexandr, 2015-06-22 13:25:37

GetJSON. How to get data from a function?

Hello, please help me solve the problem, I don’t understand why undefined is returned. How it is possible to receive the necessary value from this method?

var obj = {
  getCoords: function() {
    var self = this, arr;
    $.getJSON('data.json', function(data) {
      self.setArrays(data.array);
      arr = data;
    });
    return arr;
  }
};

console.log( obj.getCoords() );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Rytikov, 2015-06-22
@1alexandr

$.getJSON is executed asynchronously. There are 2 ways.
1. Good way : pass the callback function as an argument to .getCoords().

var obj = {
  getCoords: function(callback) {
    var self = this;
    $.getJSON('data.json', function(data) {
      self.setArrays(data.array);
      callback(data);
    });
  }
};

obj.getCoords(function (arr) {
    console.log(arr);
});

2. Bad way : use $.ajax with async options: false. This is easier, but while the call is in progress, all JavaScript and browser UI will hang.
3. Kind way : use Promise

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question