嵌套循环asynchronusly中的NodeJS,下一个循环必须只有一个被完成之后启动 [英] nested loops asynchronusly in nodejs, next loop must start only after one gets completed

查看:191
本文介绍了嵌套循环asynchronusly中的NodeJS,下一个循环必须只有一个被完成之后启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查下面的算法...

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;

我想用node.js中开发这种相同的逻辑

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

我已经尝试使用异步的foreach CONCAT foreachseries 功能。但是,所有失败的第二个层次。

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

当指针得到一个用户的 I 增大和工艺价值的接触是入门明年用户。
这是不是在等待获取联系人和放大器的过程;手机完成一个用户。并且只有下次启动后用户。我想做到这一点。

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.

推荐答案

在Node.js的,你需要使用异步方式。您code应该是这个样子:

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

这篇关于嵌套循环asynchronusly中的NodeJS,下一个循环必须只有一个被完成之后启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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