在Node.js中异步嵌套循环,下一个循环必须在一个循环完成后才开始 [英] nested loops asynchronously in Node.js, next loop must start only after one gets completed

查看:152
本文介绍了在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
});

这篇关于在Node.js中异步嵌套循环,下一个循环必须在一个循环完成后才开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆