Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to an array asynchronously in Node.js

I'm pretty new to this type of programming and I'm having some trouble populating an array from a nested call. I'm pretty sure this needs to be done using callbacks, but I'm having trouble wrapping my brain around it. Closures must also come into play here. I tried searching the web for a similar example but didn't find much.

Here is my original code. I tried a few different approaches but didn't pull it off.

TaskSchema.statics.formatAssignee = function(assignees) {
  var users = [];

  assignees.forEach(function(uid) {
    mongoose.model('User').findById(uid, function(err, user) {
      users.push({
          name: user.name.full
        , id: user.id
      });
    });
  });

  return users;
}
like image 982
sir-pinecone Avatar asked Feb 23 '23 19:02

sir-pinecone


1 Answers

I really like the following pattern (recursion is the most elegant solution to async loops):

TaskSchema.statics.formatAssignee = function(assignees, callback) {
  var acc = []
    , uids = assignees.slice()
  (function next(){
    if (!uids.length) return callback(null, acc);

    var uid = uids.pop()
    mongoose.model('User').findById(uid, function(err, user) {
      if (err) return callback(err);
      acc.push({
        name: user.name.full
      , id: user.id
      });
      next();
    });
  })();
}
like image 92
Adrien Avatar answered Feb 26 '23 21:02

Adrien