async.waterfall从不执行第二个函数

时间:2015-05-18 18:07:00

标签: javascript async.js

为什么第二个函数永远不会被执行:

async.waterfall([
    function(waterfallCb) {
        console.log("step1");
        countDocuments(db,waterfallCb);
    }, function(waterfallCb) {
        console.log("Step2");
        insertDocument(db,waterfallCb);
    }], function(err,data){
    console.log("in waterfall callback");
    db.close();
});

输出:

step1
in waterfall callback

为什么第二个函数(打印第2步)永远不会被调用?

编辑:这是countDocuments:

var countDocuments = function(db,callback){
    var collection = db.collection(colname);
    collection.find({}).toArray(function(err,docs){
        assert.equal(err, null);
        console.log("Found %d records",docs.length);
        callback(docs);
    });
};

编辑:InsertDocument:

var insertDocument = function(db, callback){
    var collection = db.collection(colname);
    collection.insertOne(sampleDoc, function(err,result){
        assert.equal(err, null);
        assert.equal(1, result.result.n);
        assert.equal(1, result.ops.length);
        console.log("inserted 1 document into the collection");
        callback(null, 'one');
    });
};

1 个答案:

答案 0 :(得分:3)

由于您使用caolan/async,因此第一个参数是错误对象,在您的情况下,如果除了null之外的其他任何内容可能会告诉异步您有错误并且不能继续。以下是文档中的示例:

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
      // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'    
});