user2783193 user2783193 - 3 months ago 15
jQuery Question

map function and not populating variable

I have following block of code

var cars = $('#mypage').data('carsdata');

if (cars == null) {
var clientId = $("input[name='ClientId']").val();
worksheet.ajax.execute('GET','/Cars/GetData/', { clientId: clientId }, function (res) {
if (res == "") {
return;
}

cars = res.Owners.filter(function (e) {
if (e.Email) {
return true;
}
return false;
}).map(function (e) {
return { key: e.Id, label: e.Email };
});

console.log("1" +cars.length); // cars lenght is 3
});


console.log("2" +cars.length); // cars is null


maybe this is too much code but the problem is that cars variable on last line is always null even though I have if statement where I checking null and in that case I'm populating that variable, where in

console.log("1" +cars.length);


cars length is 3, so it's not null. Why this cars.length is not replicated on

console.log("2" +cars.length);


is everything ok with this
map function
in a way that I'm correctly populating cars variable?

Update:

when cars is correctly loaded with data- attribute I'm getting data in following format


[Object { key=101, label="email@email.com"}, Object { key=22,
label="email2@email.com"}, Object { key=442,
label="email43@email.com"}]

Answer

That's because you are populating cars inside the callback of worksheet.ajax.execute( )

That gets called asynchronously, so your application flux is different from what you expected, and follow this order instead:

var cars = $('#mypage').data('carsdata');
//1) cars is null here

if (cars == null) {
    //...        
    //2) get inside the if statement and start the ajax call
    //   cars is null here
    worksheet.ajax.execute('GET','/Cars/GetData/', { clientId: clientId },
        function (res) {
            //...
            //4) the ajax call return his value, and cars is updated
            cars = res.Owners.filter( ... )

            //5) now cars has the correct value
            console.log("1" +cars.length); // cars lenght is 3
        })
}

//3) get out of the if statement, print the console log 
//   cars is still null here
console.log("2" +cars.length); // cars is null
Comments