有人可以向我解释为什么我无法将 booksCount 变量保存到用户 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});
其中 Users 是表中的用户列表,它是 User.find() 方法的直接结果。用户是模型。
现在,如果我尝试在 for 循环内打印 users[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});
使用 promise :
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});
});
关于node.js - Sails js -模型结果集变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42223792/