启动js -model结果集variables作用域

有人可以向我解释为什么我不能将booksCountvariables保存到用户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}); 

Where用户是从User.find()方法直接产生的表中的用户列表。 用户是模型。

现在,如果我尝试在for循环内打印用户[user] ['booksCount'],它工作正常。 但是当它超出for循环时,variables消失在空气中。 控制台打印“未定义”外循环。

因为Books.count是一个API调用,所有的API调用都是asynchronous的

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