在Node.js中异步嵌套循环,下一个循环必须在一个循环完成后才开始

在Node.js中异步嵌套循环,下一个循环必须在一个循环完成后才开始

问题描述:

检查以下算法...

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;

我想使用node.js开发同样的逻辑.

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

我尝试将异步foreachconcatforeachseries函数一起使用.但是所有这些都在第二级失败.

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

当指针获取一个用户的联系人时,值i增大,并且该过程开始于下一个用户. 它不是在等待联系的过程&一个用户完成的电话.并且只有在那之后启动下一个用户.我想实现这一目标.

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.

在node.js中,您需要使用异步方式.您的代码应类似于:

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
});