这个NodeJS代码有什么问题?nodejs带回路的异步控制流程
我有以下的NodeJS snipt。
Profile.findOne(profileId, cb) //is sync function
function getProfiles(users, cb) {
var results = [];
var n = users.length;
users.forEach(function(user, i) {
Profile.findOne(user.profileId, function(err, prf) {
if (err) {
return cb(err, null);
}
console.log(prf);
console.log(user.profileId);
results.push(prf);
if (i + 1 == n) {
console.log('looping done');
return cb(null, results);
}
});
});
}
// some where
var userslist = [{
name: 'ab',
profileId: 'daf242'
}, {
name: 'cd',
profileId: 'hg535h'
}, {
name: 'ef',
profileId: 'cvxv445'
}];
getProfiles(userslist, function(err, data) {
if (err) {
//do this
} else {
//do that
}
});
问题是结果对所述第一简档的仅型材阵列。 像
[
{username:'ab',avatarUrl:'abcd.png'}
{username:'ab',avatarUrl:'abcd.png'},
{username:'ab',avatarUrl:'abcd.png'}
]
但我期待的数组profiles不同。
我错过了什么?
试试这个:https://jsfiddle.net/rayon_1990/Ldd0mcrj/ – Rayon