이 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
}
});
문제 결과가 제 profileID가위한 만 프로필 배열되어있다.
[ {username:'ab',avatarUrl:'abcd.png'} {username:'ab',avatarUrl:'abcd.png'}, {username:'ab',avatarUrl:'abcd.png'} ]
좋아하지만 난 전혀 다른 프로파일의 배열을 기대하고있다. 무엇이 누락 되었습니까?
이 시도 약속 : https://jsfiddle.net/rayon_1990/Ldd0mcrj/ – Rayon