Was ist das Problem mit diesem NodeJS Code?nodejs async Kontrollfluss mit Schleife
Ich habe das folgende 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
}
});
Das Problem ist, die Ergebnisse sind Array von nurProfilen für das erste das Profil. wie
[
{username:'ab',avatarUrl:'abcd.png'}
{username:'ab',avatarUrl:'abcd.png'},
{username:'ab',avatarUrl:'abcd.png'}
]
aber ich erwarte Array von differnet Profile.
was fehlt mir?
Try this: https://jsfiddle.net/rayon_1990/Ldd0mcrj/ – Rayon