johnny johnny - 1 year ago 100
Node.js Question

Callback after for-loop finishes in node.js

I need some help with the asynchronous nature of node.js. I have a for loop, which collects data from the database. "result" is an array, which should then be returned to the main function.

_id : uid
}, function(error, user) {
else {
for(var j = 0; j < user.contacts.length; j++) {
if(user.contacts[j].accepted == 'true') {
_id : user.contacts[j].contactId
}, function(error, user) {
callback(null, result); // This callback executes before the for-loop ends, ofc

How can I ensure that the callback executes after the loop finished?

Answer Source

You might want to consider using helper library like async

It helps keep code more consistent..

In your case, you can look at the forEach() method

forEach(arr, iterator, callback)

The iterator is called with an item from the list and a callback for when it has finished.

Checkout the unit tests for examples