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});
});
。すべてのユーザーを取得するときに、単にユーザーのブックを埋め込むのはなぜですか? – orhankutlu
これは私がやったことです、1)本からすべての著者のリストを取り出す2)ユーザーの配列に入れる3)それぞれの書籍の数を探します。 Authorテーブルはありません。ユーザーはAuthorでもかまいません。それが私がこのようにした理由です。 – Carmen
おかげで、私はここで何ができるかを見せてください – Carmen