簡體   English   中英

Node.js異步僅執行一次回調

[英]Node.js Async only doing one callback

我只是在做節點異步工作的第一部分,我想對一個數據庫進行兩個查詢,然后一個接一個地打印結果,我的代碼如下:

console.log(req.query);

function logAllThings(err,things){
    if (err){
        console.log(err);
    } else {
        console.log(things);
    };
};


async.parallel([
    function(callback) { //This is the first task, and callback is its callback task
        Event.find({}, function(err, events) {
            logAllThings(err,events);
        });
    },
    function(callback) { //This is the second task, and callback is its callback task
        Organisation.find({}, function(err,organisations) {
            logAllThings(err,organisations);
        }); //Since we don't do anything interesting in db.save()'s callback, we might as well just pass in the task callback 
    }
], function(err) { //This is the final callback
    console.log('Both should now be printed out');
});

我的問題是第二個函數(返回組織的函數)可以很好地打印它們。 但是,盡管我知道查詢已經在其他地方測試過了,但實際上要返回事件的那個卻不返回{}。

任何幫助,將不勝感激

謝謝

您必須調用傳遞給每個瀑布函數的callback函數,否則它將不知道何時完成。 嘗試這個:

async.parallel([
    function(callback) { //This is the first task, and callback is its callback task
        Event.find({}, function(err, events) {
            if (err) return callback(err);
            logAllThings(err,events);
            callback();
        });
    },
    function(callback) { //This is the second task, and callback is its callback task
        Organisation.find({}, function(err,organisations) {
            if (err) return callback(err);
            logAllThings(err,organisations);
            callback();
        }); //Since we don't do anything interesting in db.save()'s callback, we might as well just pass in the task callback 
    }
], function(err) { //This is the final callback
    console.log('Both should now be printed out');
});

暫無
暫無

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

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