簡體   English   中英

Node.js:在繼續之前循環等待回調

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

我有一個循環,里面有一個異步調用,帶有一個回調。 為了能夠繼續前進,我需要一直觸發整個循環的回調,然后顯示循環的結果。

我試圖控制它的每一種方法都不起作用(嘗試過 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

您在回調觸發之前記錄 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');    
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM