Why the function does not return an array?

Good afternoon, help to solve the problem, the bottom line, trying to set an array of dates when booting, but for some reason, the function returns undefined

var array = new Array();

 function load_reservation(stock, year = null, month = null){

 $.post( "'.Url::to(['site/ajax-load-reservation']).'", {stock: stock, "year": year, "month": month }, function( data ) {

if(data.result==1){
 return data.array; 
}
 else return [];
 }, "json");
}

$(".book").each(function(){
 var id = $(this).attr("data-stock_id");
 array[id] = load_reservation(id);

console.log(array[id]);
 });


php returns the array in json format
I need to get data loaded into an array var array

Thanks in advance
July 8th 19 at 11:12
1 answer
July 8th 19 at 11:14
Solution
A function you do not return. There is async. In $.post call the callback with the results.

var array = [];

function load_reservation(stock, year, month, callback) {

 $.post("'.Url::to(['site/ajax-load-reservation']).'", {stock: stock, "year": year, "month": month}, function (data) {

 if (data.result == 1) {
callback(data.array);
}
 else callback([]);
 }, "json");
}

$(".book").each(function () {
 var id = $(this).attr("data-stock_id");
 load_reservation(id, null, null, function (result) {
 array[id] = result;
console.log(array[id]);
});
});
ReferenceError: callback is not defined
else callback([]); - creola.Murray72 commented on July 8th 19 at 11:17
TypeError: callback is not a function
else callback([]); - creola.Murray72 commented on July 8th 19 at 11:20
: call load_reservation correct, I forgot about the null - Liam_Barrows commented on July 8th 19 at 11:23
Thank you very much!!!
$(".book").each(function(){
var id = $(this).attr("data-stock_id");
load_reservation(id, null, null, function(result){
array[id] = result;
console.log(array[id]);
});
}); - creola.Murray72 commented on July 8th 19 at 11:26

Find more questions by tags JavaScriptArrays