0

hello to all I am new on this I try save the result on outside variable to use late on coming from a petition using jsonp

var user = null;

gettingUser()

function gettingUser() {
$.getJSON("https://myapi.com/users/profile/?userid=" + id + "&jsonp=?", function (json) {
        getData(json);
});


console.log(user) // this is null here why ?
}


getData(data){
 user = data
}

all ways I get null in the var user I need help thanks

  • Move the console.log(user) inside the getData(data) function after the user=data line. That is where the value of user is populated. – Nawed Khan May 08 '19 at 17:27
  • `$.getJSON` function is async function, so there is no problem in `user` is null – Wang Liang May 08 '19 at 17:28
  • Please use `console.log(user) ` in `function (json) { ...}` – Wang Liang May 08 '19 at 17:29
  • yes I move the console.log to function json I get my data the problem is I can use outside like I have on my example – Alfredo Izquierdo May 08 '19 at 17:31
  • To answer the question 'Why is user null after the getJSON() call?' The answer is because the getJson call is asynchronous meaning the system goes off to run the call but continues without holding the user on line. so the next line is executed even before a response comes back from the ajax call. That is why we have callback function which is called only AFTER the result has returned. – Nawed Khan May 08 '19 at 17:32
  • so what is the better way for handle this situation ? – Alfredo Izquierdo May 08 '19 at 17:34
  • It is the best way to handle the situation... read the value after callback. That is console.log(user) inside getData(data) function. – Nawed Khan May 08 '19 at 17:37
  • yes but them on Inside getData(data) I am storage the result user=data but how I can use it variable late wherever I need it ? – Alfredo Izquierdo May 08 '19 at 17:40

0 Answers0