javascript - nodejs async control flow with loop -


what problem nodejs code?

i have following 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);       }     });   }); }  //  var userslist = [{   name: 'ab',   profileid: 'daf242' }, {   name: 'cd',   profileid: 'hg535h' }, {   name: 'ef',   profileid: 'cvxv445' }]; getprofiles(userslist, function(err, data) {   if (err) {     //do    } else {     //do   } }); 

the problem results array of only profiles first profileid.

 [       {username:'ab',avatarurl:'abcd.png'}       {username:'ab',avatarurl:'abcd.png'},       {username:'ab',avatarurl:'abcd.png'}     ] 

but expecting array of differnet profiles.

what missing?

you're mixing synchronous , asynchronous code here. foreach loop running synchronously, profile.findone method asynchronous. calls callback passed initial function. should @ using async asynchronous loop.

however, there many things in question suggest haven't grasped asynchronous nature of node.js yet. try reading on topic, such callback hell.


Comments