简体   繁体   English

Node.js中的异步迭代问题

[英]Async issues with iteration in Node.js

I found myself hitting the issue of iterating through an array, triggering async ops for each item that call my callbacks with arrays that I'm iterating again... Of course before going to the next item, you need to wait for the previous to finish. 我发现自己遇到了遍历数组的问题,触发了每个项目的异步操作,这些项​​目使用我正在再次遍历的数组来调用我的回调。当然,在转到下一项之前,您需要等待上一个完。 And if an error occurs while processing an item, you have to stop and exit all enclosing loops. 而且,如果在处理项目时发生错误,则必须停止并退出所有封闭循环。

The code I write to handle these situations, is easy to write but not easy to read/maintain. 我为处理这些情况而编写的代码很容易编写,但不容易阅读/维护。 For completeness of this question I'm currently using a method I wrote that looks like this: 为完整起见,我目前使用的方法如下:

iterate(items, item_callback, ended_callback);

where the item_callback looks like this: 其中item_callback如下所示:

function(item, next_item, stop) {

    //do your stuff with `item` here...

    //return next_item() to go forward
    //return stop() to break
}

I'm wondering that maybe I'm missing a better technique of iterating in node.js. 我想知道也许我错过了在node.js中进行迭代的更好技术。

Example time: 时间示例:

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: How to iterate in node.js so that it works with both async code and the classic sync code? TL; DR:如何在node.js中进行迭代,以使其与异步代码和经典同步代码一起使用?

PS: I'm sure some users will answer something along the use the async module. PS:我确信某些用户会在使用async模块的过程中回答一些问题。 I know about it. 我知道 I don't like how my code looks like when using it. 我不喜欢使用代码时的样子。 It's even less maintainable than with my current solution. 它比我当前的解决方案更难维护。 I need something better. 我需要更好的东西。

There are a ton of node.js flow control libraries for dealing with async operations. 有大量的node.js流控制库用于处理异步操作。 They all have slightly different approaches and syntactic sugar, but async is probably the most popular. 它们都有不同的方法和语法糖,但是async可能是最受欢迎的方法。 I prefer Step for it's power-to-weight ratio. 我更喜欢Step因为它的功率重量比。 :) :)

Your example if I get correctly is mongoose usage. 如果我正确理解,您的例子是猫鼬用法。 See following solution that's based on promises: Node.js deferred promisify + mongoose 请参阅以下基于Promise的解决方案: Node.js延迟Promisify +猫鼬

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM