Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

nested loops asynchronusly in nodejs, next loop must start only after one gets completed

nested loops asynchronusly in nodejs, next loop must start only after one gets completed

Problem

Check below algorithm...

users = getAllUsers();
for(i=0;i

I want to develop such same logic using node.js.

I have tried using async with foreach and concat and foreachseries functions. But all fails in second level.

While pointer is getting contacts of one user, value of i increases and process is getting started for next users. It is not waiting for the process of getting contacts & phones to complete for one user. and only after that starting next user. I want to achieve this.

Actually I want to get the users object with proper

Means all the sequences are getting ruined, can anyone give me general idea how can I achieve such series process. I am open to change my algorithm also.

Problem courtesy of: Maulik Vora

Solution

In node.js you need to use asynchronous way. Your code should look something like:

var processUsesrs = function(callback) {
    getAllUsers(function(err, users) {
        async.forEach(users, function(user, callback) {
            getContactsOfUser(users.userId, function(err, contacts) {
                async.forEach(contacts, function(contact, callback) {
                    getPhonesOfContacts(contacts.contactId, function(err, phones) {
                        contact.phones = phones;
                        callback();
                    });
                }, function(err) {
                    // All contacts are processed
                    user.contacts = contacts;
                    callback();
                });
            });
        }, function(err) {
            // All users are processed
            // Here the finished result
            callback(undefined, users);
        });
    });
};

processUsers(function(err, users) {
    // users here
});
Solution courtesy of: Vadim Baryshev

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

nested loops asynchronusly in nodejs, next loop must start only after one gets completed

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×