0

I was trying to return a string from a function to be available as a global variable using the following code, but I didn't realize what's wrong.

Is there a way to get the JSON result outside the function?

var out = '';
function getAgregData() {
  $.getJSON('http://172.16.13.247:5002/webservice//?module=1', function(data) {
    const sourceObject = data;
    const sourceObjectKeys = Object.keys(sourceObject);
    //console.log('AgrKeys: ',sourceObjectKeys);
    let agr = {};
    sourceObjectKeys.forEach((key, i) => {
      agr[key] = sourceObject[key]['agreg'];
    });
    let out = JSON.stringify(agr);
    console.log('Output inside function:', out); // <=== Here I got out variable printed on Console.
    return out;
  });
}
var test = getAgregData();
console.log('Output outside function: ', test); // <=== Here I didn't get out inside test variable printed on Console.
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Marcio Lino
  • 379
  • 2
  • 15
  • When your console.log outside the function is called, the getJSON is not finished because it is asynchronous. – Eldynn Jul 24 '20 at 11:52
  • How can I solve this? Thanks! – Marcio Lino Jul 24 '20 at 11:58
  • You can return from your function the getJSON, then use the variable test with something like: test.then(() => console.log('output: ', out)). In any case I strongly advice you to refactor your code by looking at how asynchrone / Promise work :) – Eldynn Jul 24 '20 at 12:03

0 Answers0