這個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