我有以下代码块
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
也许这是太多的代码,但问题是最后一行的汽车变量总是为空,即使我有if语句,我检查null,在那种情况下,我填充该变量,在
console.log("1" +cars.length);
汽车长度是3,所以它不是空的。为什么这个cars.length没有在
上复制console.log("2" +cars.length);
这个map function
是否可以正常填充汽车变量?
更新
当汽车正确加载数据属性时,我会以下列格式获取数据
[Object {key = 101,label =" email@email.com"},Object {key = 22, label =" email2@email.com"},Object {key = 442, 标签=" email43@email.com"}]
答案 0 :(得分:1)
那是因为你在cars
的回调中填充了worksheet.ajax.execute( )
异步调用,因此您的应用程序流量与预期不同,请遵循以下顺序:
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