2013-03-25 62 views
1

我試圖使用async waterfall method,但是當它到達其中一個函數時,它會掛起。我懷疑這是因爲save()操作對於執行上下文來說太慢了,但這就是爲什麼我開始使用異步的瀑布,所以我可以等待返回的值直到它進入系列中的下一個函數(傳遞正確的數據與它在我的情況下將是counted)。調用貓鼬時async.js掛起的瀑布方法保存方法

//在我的用戶控制:

async.waterfall([ 
    function(callback) { 
    getSubmission(id, function(submission) { 
     if (submission) { 
     callback(null, submission); 
     } 
    }); 
    }, 
    function(submission, callback) { 
    var submissionId = submission._id; 

    getViews(submissionId, ip, function(count) { 
     if (count) { 
     callback(null, count, submissionId); 
     } 
    }); 
    }, 
    // Those top two functions work perfectly passing what 
    // I need to this one which is where I'm having trouble 
    function(views, submissionId, callback) { 
    // addView is called because it is actually 
    // inserting a row in the db, but never returns from the caller 
     addView(submissionId, ip, function(added) { 
     // this callback doesn't fire 
     if (added) { 
      callback(null, added); 
     } 
     }); 
    }, 
    function(added, callback) { 
    console.log(added); 
    } 
]); 

這是addView()是什麼(也內用戶控制器,它就是以前async.waterfall代碼也爲):

var addView = function(submissionId, ip, callback) { 
    Submission.addView({ 
    submissionId : submissionId, 
    ip: ip 
    }, function(err, counted) { 
    if (err) { 
     throw err; 
    } 

    if (counted) { 
     callback(counted); 
    } 
    }); 
}; 

這是什麼它在調用Submission.addView()時調用(在我的提交模型文件中):

exports.addView = function(obj, fn) { 
    var ip = obj.ip, 
     submissionId = obj.submissionId, 
     submissionView = new SubmissionView(obj); 
// it gets to this point 

    submissionView.save({ 
    ip : ip, 
    submission_id : submissionId 
    }, function(err, counted) { 
    fn(err, counted); 
    }); 
}; 

回答

4

每當異步「掛起」時,通常都是因爲沒有調用回調。

您需要確保您在所有代碼路徑中調用回調。我還建議你保留任何異步回調的第一個參數是一個錯誤,即使你不使用它,因爲這是整個node.js使用的模式。一些模塊依賴於這種模式。例如域。

如果你把下面的變化,那麼我會期待一些錯誤的地方彈出:

getSubmission(id, function(submission) { 
     if (submission) { 
     callback(null, submission); 
     } 
    }); 

應該是這樣的:

getSubmission(id, function(err, submission) { 
     if(err){ 
     return callback(err); 
     } 
     if (!submission) { 
     return callback('no submission found'); 
     } 
     callback(null, submission); 
    }); 
+0

原來我是路過的2種方法Mongoose'save()'方法,但它只需要一個,這樣就可以擺脫我通過修復它的參數。 – 2013-03-26 19:51:01