Adding to an array asynchronously in Node.js

I am new to this type of programming, and I am having trouble populating an array from a nested call. I'm sure this needs to be done using callbacks, but I am having problems wrapping my brain. It should also be closed here. I tried searching the Internet for a similar example, but did not find much.

Here is my original code. I tried several different approaches, but did not.

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; } 
+4
source share
3 answers

I really like the following pattern (recursion is the most elegant solution for asynchronous 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(); }); })(); } 
+6
source

Check out async , it has an asynchronous foreach loop.

Edit

Here is the foreach method from the asynchronous library

 async.forEach = function (arr, iterator, callback) { if (!arr.length) { return callback(); } var completed = 0; _forEach(arr, function (x) { iterator(x, function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed === arr.length) { callback(); } } }); }); }; var _forEach = function (arr, iterator) { if (arr.forEach) { return arr.forEach(iterator); } for (var i = 0; i < arr.length; i += 1) { iterator(arr[i], i, arr); } }; 
+2
source

you can do something like:
Give formatAssignee a callback.
Count how many users you need to click on users.
After you press the last one, call the callback with the users parameter.

0
source

All Articles