Sails js -模型结果集变量范围
Sails js -model resultset variable scope
有人可以向我解释为什么我不能将 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 是来自 table 的用户列表,这是 User.find() 方法的直接结果。用户即模型。
现在,如果我尝试在 for 循环中打印 users[user]['booksCount'],它工作正常。但是当它超出 for 循环时,变量就消失得无影无踪了。控制台在 for 循环外打印 'undefined'。
因为 Books.count 是一个 API 调用并且所有 API 调用都是异步的所以 In
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});
});
有人可以向我解释为什么我不能将 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 是来自 table 的用户列表,这是 User.find() 方法的直接结果。用户即模型。
现在,如果我尝试在 for 循环中打印 users[user]['booksCount'],它工作正常。但是当它超出 for 循环时,变量就消失得无影无踪了。控制台在 for 循环外打印 'undefined'。
因为 Books.count 是一个 API 调用并且所有 API 调用都是异步的所以 In
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});
});