【问题标题】:Node.js: waiting for callbacks in a loop before moving onNode.js:在继续之前循环等待回调
【发布时间】:2011-10-09 01:01:08
【问题描述】:

我有一个循环,里面有一个异步调用,带有一个回调。为了能够继续前进,我需要一直触发整个循环的回调,然后显示循环的结果。

我尝试过的所有控制方法都不起作用(尝试过 Step、Tame.js、async.js 等) - 关于如何继续前进的任何建议?

array = ['test', 'of', 'file'];
array2 = ['another', 'array'];

for(i in array) {
    item = array[i];
    document_ids = new Array();

    for (i2 in array2) {
        item2 = array2[i2];
        // look it up
        mongodb.find({item_name: item2}).toArray(function(err, documents {
            // because of async,
            // the code moves on and calls this back later
            console.log('got id');
            document_ids.push(document_id);
        }))
    }

    // use document_ids
    console.log(document_ids); // shows []
    console.log('done');
}

// shows:
// []
// done
// got id
// got id

【问题讨论】:

    标签: asynchronous node.js


    【解决方案1】:

    您在回调触发之前记录 document_ids。您必须跟踪运行了多少回调才能知道何时完成。

    一种简单的方法是使用计数器,并检查每个回调的计数。

    以你为例

    var array = ['test', 'of', 'file'];
    var array2 = ['another', 'array'];
    var document_ids = [];
    
    var waiting = 0;
    
    for(i in array) {
        item = array[i];
    
        for (i2 in array2) {
            item2 = array2[i2];
            waiting ++;
    
            mongodb.find({item_name: item2}).toArray(
                function(err, document_id) {
                    waiting --;
                    document_ids.push(document_id);
                    complete();
                })
            );
        }
    }
    
    function complete() {
        if (!waiting) {
            console.log(document_ids);
            console.log('done');    
        }
    }
    

    【讨论】:

    • 非常感谢!我在 async.js 的帮助下修改了它并让它工作了。
    • 它工作正常只是想知道你为什么使用waiting --; 我认为每一行的评论都应该很好
    • @AnilYadav 他正在等待 --;在每一行上减少每个回调中的值,最后它将为0。如果满足完整函数内部的条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2021-12-26
    • 2020-05-19
    • 1970-01-01
    相关资源
    最近更新 更多