我有一个简单的销售应用程序,我在其中的 Controller 中查询数据库。检索结果,使用 async.each 函数对数据进行一些操作,然后将数组发送到 View 。
即使我的日志显示数组中的数据,但我的 View 收到的是一个空白数组。
"index": function(req, res, next) {
Sales.find().sort("createdAt DESC").done(function(err, sales) {
if (err) {
res.send("An error has occured. :(");
} else {
if (!sales) {
req.session.flash = {
err: {
message: "You have no billing as of now.",
style: "alert-info"
}
}
} else {
var bills = [];
async.eachSeries(sales, function(thisSale, callback) {
if (!bills[thisSale.billingNo]) {
bills[thisSale.billingNo] = {
id: thisSale.billingNo,
createdAt: thisSale.createdAt,
total: (thisSale.quantity * thisSale.price),
location: thisSale.location,
};
} else {
bills[thisSale.billingNo].total += (thisSale.quantity * thisSale.price);
}
callback();
}, function(err) {
if (err) {
console.log('Something went wrong !');
exit();
} else {
res.send({
billing: bills
});
console.log("=====\nBILL\n=====\n", bills);
}
});
}
}
});
},
我用 res.send 替换了 res.view 来调试我的代码,在客户端我只收到这个:
{
"billing": []
}
尽管控制台日志显示:
=====
BILL
=====
[ '53b95fdc1f7a596316f37af0': { id: '53b95fdc1f7a596316f37af0',
createdAt: Sun Jul 06 2014 20:10:28 GMT+0530 (IST),
total: 6497,
location: 'Location A' },
'53b8f7c81f7a596316f37aed': { id: '53b8f7c81f7a596316f37aed',
createdAt: Sun Jul 06 2014 12:46:24 GMT+0530 (IST),
total: 6497,
location: 'Location A' } ]
谁能帮我弄清楚我做错了什么?
最佳答案
我尝试调试问题,发现我无法访问 bills[0],然后在数组 bills 上使用 forEach 循环,发现它无法运行 for each 循环。
将变量 bills 从数组更改为对象时,问题得到解决。
我不完全确定为什么会发生这种情况,或者为什么我在向数组添加变量时遇到问题,但更改
var bills = [];
到
var bills = {};
解决了问题。
关于javascript - Sails.js 应用程序变量数据未显示在 View 中,即使日志显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24597806/