The problem with return?

Can't understand what the problem is
function getLang(lang) {
 $.getJSON(gInit['url'] + '/lang/'+getCookie('lang')+'.json', function(data) {
 var items = [];
 $.each(data, function(key, val) {
 if(key == lang) {
 items += val;
}
});
 return items;
});
}

When calling from the console getLang("users") me prints out undefined, what could be the problem?
July 12th 19 at 16:52
2 answers
July 12th 19 at 16:54
Solution
Use "promises".
https://learn.javascript.ru/promise
caniuse.com/#feat=promises

https://github.com/dfilatov/vow, etc.

Or jQuery.Deferred:
function getLang(lang) {
 var d = $.Deferred();

 $.getJSON(gInit['url'] + '/lang/'+getCookie('lang')+'.json', function(data) {
 var items = [];
 $.each(data, function(key, val) {
 if(key == lang) {
items.push(val);
}
});
d.resolve(items);
});

 return d.promise();
}

var test = getLang("users");
test.done(function (data) {
console.log(data);
});
July 12th 19 at 16:56
The problem is that you do not fully understand how they work callback functions and asynchronous calls.
When calling from the console getLang("users") does no return does not work. Calls the function $.getJSON and all the getLang function terminates.
Parallel to this runs a query gInit['url'] + '/lang/'+getCookie('lang')+'.json' (it can be done, for example, a few seconds) and upon completion triggers your code, until you reach the return, but the return value has no one.
Replace: return alert or console.log and you'll understand.
What if I call it within another function? console me to debug me to the console in the right field inserts undefine - Ethan_Kuhic commented on July 12th 19 at 16:59
You need to do the following. You call getLang("users") by some event (e.g. clicking a button), and instead return items; you can print out the received data somewhere in the field/form/div/etc. Just a note, you first items is declared as an array, and then you add to items in the string/number. - Demario.Bergstr commented on July 12th 19 at 17:02

Find more questions by tags jQueryJavaScriptJSON