2017-02-14 8 views
2

booksCount変数をユーザーjsonオブジェクトに保存できない理由を誰かに説明することはできますか?ここに私のコードがあります帆jsモデルの結果セット変数スコープ

ここで、UsersはUser.findユーザーはモデルです。

私はユーザーの[ユーザー] ['booksCount']をforループの内側に印刷しようとするとうまくいきます。しかし、それがforループの外に出ると、変数は薄い空気に消えます。コンソールはforループの外側に 'undefined'を表示します。

+2

。すべてのユーザーを取得するときに、単にユーザーのブックを埋め込むのはなぜですか? – orhankutlu

+0

これは私がやったことです、1)本からすべての著者のリストを取り出す2)ユーザーの配列に入れる3)それぞれの書籍の数を探します。 Authorテーブルはありません。ユーザーはAuthorでもかまいません。それが私がこのようにした理由です。 – Carmen

+0

おかげで、私はここで何ができるかを見せてください – Carmen

答えて

1

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}); 
}); 
+0

それは、ありがとう – Carmen