asynchronous问题与Node.js迭代

我发现自己碰到了遍历数组的问题,触发了每个项目的asynchronous操作,这些操作调用了我正在重复迭代的数组的callback函数。当然,在进入下一个项目之前,您需要等待之前的完。 如果在处理项目时发生错误,则必须停止并退出所有封闭循环。

我写的处理这些情况的代码很容易编写,但不容易读取/维护。 为了完整的这个问题,我正在使用我写的这样的方法:

iterate(items, item_callback, ended_callback); 

item_callback看起来像这样:

 function(item, next_item, stop) { //do your stuff with `item` here... //return next_item() to go forward //return stop() to break } 

我想知道,也许我错过了一个更好的node.js迭代技术。

示例时间:

 User.find(function(err, users) { //iterate through users: how? //first attempt: for for(var i in users) { //simple stuff works here... but if I call something async... what do I do? //like iterating through friends User.find({friend:users[i]._id}, function(err, friends) { if(err) { //handle error: how is best to do this? } //this might end after the next user is selected... and might break things }); } }); 

TL; DR:如何在node.js中进行迭代,使其能够同时处理asynchronous代码和经典同步代码?

PS:我确定有些用户会在使用async模块的时候回答一些问题。 我知道这件事。 我不喜欢我的代码在使用时的样子。 这比我目前的解决scheme更难以维护。 我需要更好的东西。

有大量的node.jsstream控制库用于处理asynchronous操作。 他们都有略微不同的方法和语法糖,但async可能是最stream行的。 我更喜欢Step因为它的功率重量比。 🙂

你的例子,如果我得到正确的mongoose用法。 请参阅以下基于承诺的解决scheme: Node.js推迟promisify +mongoose