Node.js Sails js-模型结果集变量范围
有人能解释一下为什么我不能将booksCount变量保存到users json对象中吗?这是我的密码Node.js Sails js-模型结果集变量范围,node.js,sails.js,waterline,Node.js,Sails.js,Waterline,有人能解释一下为什么我不能将booksCount变量保存到users json对象中吗?这是我的密码 for(var user in users){ Books.count({author: users[user]['id']}).exec(function(err, count){ users[user]['booksCount']=count; }); } return res.view('sellers', {data: users});
for(var user in users){
Books.count({author: users[user]['id']}).exec(function(err, count){
users[user]['booksCount']=count;
});
}
return res.view('sellers', {data: users});
其中Users是表中的用户列表,该列表是User.find()方法的直接结果。用户就是模型
现在,如果我试着在for循环中打印用户[user]['booksCount',效果很好。但当它超出for循环时,变量消失在稀薄的空气中。控制台在for循环外部打印“未定义”。因为Books.count是一个API调用,所有API调用都是异步的,所以在
for(var user in users){
// It Will call the Books.count and leave the callback Function without waiting for callback response.
Books.count({author: users[user]['id']}).exec(function(err, count){
users[user]['booksCount']=count;
});
}
//As callback result didn't came here but the controll came here
// So, users[user] will be undefined here
return res.view('sellers', {data: users});
使用承诺:
async.forEachOf(users, function (value, user, callback) {
Books.count({author: users[user]['id']}).exec(function(err, count){
users[user]['booksCount']=count;
callback(err);
// callback function execute after getting the API result only
});
}, function (err) {
if (err) return res.serverError(err.message); // Or Error view
// You will find the data into the users[user]
return res.view('sellers', {data: users});
});
因为你是异步的。获取所有用户时,为什么不直接填充用户书籍?这就是我所做的,1)从书籍中获取所有作者列表2)填充用户数组3)查找每个用户的书籍计数。没有作者表。用户也可以是作者。这就是我这样做的原因。谢谢,让我看看我能在这里做些什么。你能展示你的模型吗?