在nodejs中asynchronous嵌套循环,下一个循环只有在完成后才能启动
检查下面的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开发同样的逻辑。
我曾尝试使用foreach
和concat
和foreachseries
函数的asynchronous 。 但都在第二级失败。
当指针正在获取一个用户的联系人时, i
值增加,下一个用户的进程正在开始。 它并不等待为一个用户完成联系人和电话的完成过程。 只有在下一个用户开始之后。 我想实现这一点。
其实我想得到正确的用户对象
意味着所有的序列都被破坏了,谁能给我一个总体思路,我怎么能够实现这样的系列化过程。 我打开也改变我的algorithm。
在node.js中,您需要使用asynchronous方式。 你的代码应该是这样的:
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 });