简体   繁体   English

Node.js:在继续之前循环等待回调

[英]Node.js: waiting for callbacks in a loop before moving on

I have a loop that has an asynchronous call inside it, with a callback.我有一个循环,里面有一个异步调用,带有一个回调。 To be able to move on, I need the callback to fire for the entire loop all the way through, to then display the results of the loop.为了能够继续前进,我需要一直触发整个循环的回调,然后显示循环的结果。

Every way I've tried to control this doesn't work (have tried Step, Tame.js, async.js, and others) - any suggestions on how to move forward?我试图控制它的每一种方法都不起作用(尝试过 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

You're logging document_ids before your callbacks fire.您在回调触发之前记录 document_ids。 You have to keep track of how many callbacks you've run to know when you're done.您必须跟踪运行了多少次回调才能知道何时完成。

An easy method is to use a counter, and to check the count on each callback.一个简单的方法是使用计数器,并检查每个回调的计数。

Taking your example以你为例

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

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

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