当用户登录时,我向他发送用户信息。
var userstuff00 = findSub(user['id']);
userstuff00.then(function(sub){
for(var i in sub){
var userstuff01 = findSub(sub[i.toString()]['id']);
userstuff01.then(function(sub2){
for(var i2 in sub2){
//here i is the last object in sub but i2 is for the first i
console.log(sub[i.toString()]);
console.log(sub2[i2.toString()]);
}
});
}
});这是findSub函数,其中用户集合是mongodb表:
function findSub(stuffCode){
var tempMembers = usercollection.find({'stuff ': stuffCode});
return tempMembers;
}这是用户对象:
user{
id,
name,
stuff,
subMember[] //list of users where their stuff equals to this users id
}我想在这个用户中添加每个sub2,subMember,但是i的id不等于i2的内容(我不能在其他i的子成员中添加i2 )。
如何获得第一个i的子成员,然后为第二个i找到子成员?
我的目标是将用户作为子成员的用户列表,而这些用户(子成员级别1)有子成员(子成员级别2)等等(直到级别10):家谱
发布于 2017-02-08 16:05:32
在使用异步代码时,这是一个典型的问题:同步代码将在任何异步代码之前完成。所以这个循环:
for(var i in sub)..。将在执行其内部的任何then回调之前完成。因此,当其中一个被执行时,i的值已经是sub的长度了。
为了能够在调用then时使用I的值(而不是它的回调),有不同的解决方案。其中之一是使用let i而不是var i,因为它将在for循环的每次迭代中定义一个不同的变量。也可以将i的值作为参数绑定到then回调:
userstuff01.then(function(i, sub2){
// ^^^ added parameter
for(var i2 in sub2){
//here i is the last object in sub but i2 is for the first i
console.log(sub[i.toString()]);
console.log(sub2[i2.toString()]);
}
}.bind(null, i));
// ^^^^^^^^^^^ bind the parameter value to the current value of i.https://stackoverflow.com/questions/42112441
复制相似问题