1

I have this little piece of code


JS

function insertDataIntoTable(jsonUrl, Id) {
    var obj;
    $.getJSON(jsonUrl, function(data){
        console.log("1: "+data.elem[Id]);  //outputs the correct object
        obj= data.elem[Id];
        console.log("2: "+obj);            //still is correct
    });
    console.log("3: "+obj);                //now it logs "undefined"
}

which refers to a well-formed JSON which don't wanna post if not really necessary. I hope someone can help me anyway.

davide m.
  • 452
  • 4
  • 19
  • 4
    it's all about the asynchrony - try putting `async ` before `function insertDataIntoTable` and `await` before `$.getJSON` - though you don't need to .. you know where the data is available, inside the callback - so do what you need there – Bravo Oct 27 '18 at 09:04
  • Want to add here is that if you add a number to console log it will be clear that the second one is called before the one inside the getJSON callback. So yes, why do you need it to be available after the getJSON out of the callback? Try to set the correct target and we'll be able to help. – extempl Oct 27 '18 at 09:13
  • function insertDataIntoTable(jsonUrl, Id) { let obj; let promice = new Promise((resolve) => { $.getJSON(jsonUrl, function(data) { console.log("1: " + data.elem[Id]); //outputs the correct object obj = data.elem[Id]; console.log("2: " + obj); resolve(obj) //still is correct }); }) promice.then((obj) => { console.log("3: " + obj); //now it logs "undefined" }) } – Petrashka Siarhei Oct 27 '18 at 09:22

2 Answers2

2
function insertDataIntoTable(jsonUrl, Id) {
var obj;
var callback = function(){
    console.log("3: "+obj);                //now it logs "undefined"
}
$.getJSON(jsonUrl, function(data){
    console.log("1: "+data.elem[Id]);  //outputs the correct object
    obj= data.elem[Id];
    console.log("2: "+obj);            //still is correct
    callback();
});
}
iman kazemi
  • 522
  • 5
  • 15
  • it will `undefined ` as when your **callback** function was defined value of `obj` was `undefined` because **callback** function is a **closure** – Juned Lanja Oct 27 '18 at 09:22
0

This is because $.getJSON is asynchronous by nature. So when insertDataIntoTable method is called it will execute in following step.

  1. define var obj;
  2. do the ajax call to your jsonUrl using $.getJSON
  3. console.log("3: "+obj); Here your obj will be undefined as its not defined any value yet
  4. execute the success/failure callback of your ajax call (using $.getJSON )where your getting console.log("1: "+data.elem[Id]); and console.log("2: "+obj); absolutely right

There is nothing wrong in your code.

If you want to make above code synchronous then you can do by following methods:

1) use $.ajax using async:false

function insertDataIntoTable(jsonUrl, Id) {
    var obj;
    $.ajax({
      dataType: "json",
      url: jsonUrl,
      data: data,
      async: false,
      success: function(data) {
        obj = data.elem[Id]
      }
    });
    console.log(obj);
  }

2). If your using es6 or higher the use async & await

let insertDataIntoTable = async (jsonUrl, Id) => {
    let obj;
    let data = await $.getJSON(jsonUrl);
    obj = data.elem[Id];
  }
Juned Lanja
  • 1,466
  • 10
  • 21