Sorry for asking noob question (Below code is associated with express framework and mongoose DB)
很抱歉询问noob问题(下面的代码与快速框架和mongoose DB相关)
I'm trying to loop through the array 'Users' that contains usernames, then I try to match them on mongoose database to get the school and the grade for each user. Then combine them into on final array called UsersInfoFinal .
我正在尝试遍历包含用户名的数组'Users',然后我尝试在mongoose数据库上匹配它们以获得学校和每个用户的等级。然后将它们组合到名为UsersInfoFinal的最终数组中。
var Users = ['peter', 'john'];
var UsersInfoFinal = [];
for (i = 0; i < Users.length; i++){
userModel.findOne ({username: Users[i]}, 'username school grade', function (error, UserInfo) {
UsersInfoFinal .push([UserInfo.username, UserInfo.school, UserInfo.grade]);
});
}
console.log(UsersInfoFinal );
The console should print [[peter, MIT, 95], [john, Royal Academy, 89]]
, however, the console still prints []
, the variable UsersInfoFinal isn't modified.
控制台应该打印[[peter,MIT,95],[john,Royal Academy,89]],但是,控制台仍然打印[],不修改变量UsersInfoFinal。
Why is that? Is there a way to modify the variable after the loop? Help please I'm really new to node.js and MongoDB and have been stuck for hours :S
这是为什么?有没有办法在循环后修改变量?请帮助我对node.js和MongoDB真的很新,并且已经被困了几个小时:S
Thanks!
1 个解决方案
#1
1
Here I will give you a very simple pattern for use in cases like this. Try this code:
在这里,我将为您提供一个非常简单的模式,以便在这种情况下使用。试试这段代码:
var Users = ['peter', 'john'];
var UsersInfoFinal = [];
var usersWaiting = 0;
function allDone() {
console.log(UsersInfoFinal);
}
for (i = 0; i < Users.length; i++){
usersWaiting++;
userModel.findOne ({username: Users[i]}, 'username school grade', function (error, UserInfo) {
usersWaiting--;
UsersInfoFinal .push([UserInfo.username, UserInfo.school, UserInfo.grade]);
if (usersWaiting == 0) {
allDone();
}
});
}
This is a pretty common pattern for managing multiple asynchronous calls in ecmascript environments. There may be a better way to do it but it sure gets the job done.
这是在ecmascript环境中管理多个异步调用的一种非常常见的模式。可能有更好的方法,但它确实可以完成工作。
#1
1
Here I will give you a very simple pattern for use in cases like this. Try this code:
在这里,我将为您提供一个非常简单的模式,以便在这种情况下使用。试试这段代码:
var Users = ['peter', 'john'];
var UsersInfoFinal = [];
var usersWaiting = 0;
function allDone() {
console.log(UsersInfoFinal);
}
for (i = 0; i < Users.length; i++){
usersWaiting++;
userModel.findOne ({username: Users[i]}, 'username school grade', function (error, UserInfo) {
usersWaiting--;
UsersInfoFinal .push([UserInfo.username, UserInfo.school, UserInfo.grade]);
if (usersWaiting == 0) {
allDone();
}
});
}
This is a pretty common pattern for managing multiple asynchronous calls in ecmascript environments. There may be a better way to do it but it sure gets the job done.
这是在ecmascript环境中管理多个异步调用的一种非常常见的模式。可能有更好的方法,但它确实可以完成工作。