Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested loops asynchronously in Node.js, next loop must start only after one gets completed

Check below algorithm...

users = getAllUsers();
for(i=0;i<users.length;i++)
{
    contacts = getContactsOfUser(users[i].userId);
    contactslength = contacts.length;
    for(j=o;j<contactsLength;j++)
    {
         phones = getPhonesOfContacts(contacts[j].contactId);
         contacts[j].phones = phones;
    }
    users[i].contacts = contacts;
}

return users;

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

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

While pointer is getting contacts of one user, a value of i increases and the 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 the next user. I want to achieve this.

Actually, I want to get the users to object with proper

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

like image 383
Maulik Vora Avatar asked Mar 15 '12 07:03

Maulik Vora


People also ask

How many times a nested loop executes?

The outer loop executes 2 times and each time the outer loop executes the inner loop executes 3 times so this will print 2 * 3 = 6 stars. The formula for calculating the number of times the inner loop executes is the number of times the outer loop repeats multiplied by the number of times the inner loop repeats.

How does node js work asynchronously?

NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications. Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.

How nested for loop is executed?

A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.

What happens if you use await inside a loop and what are the alternatives?

When evaluate for loop, we have await promise inside the async function, the execution will pause until the await promise is settled. So, you can think of that the files are read one by one in a determined order. Sometimes, we really need the the async functions to be executed in a sequential order.


1 Answers

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
});
like image 87
Vadim Baryshev Avatar answered Nov 07 '22 02:11

Vadim Baryshev