【问题标题】:async.waterfall never executes second functionasync.waterfall 从不执行第二个函数
【发布时间】:2015-07-30 08:43:36
【问题描述】:

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

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

编辑:插入文档:

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

【问题讨论】:

  • 我的猜测:countDocuments 不会调用第一个 waterfallCb
  • 你在使用caolan/async吗?第一个参数是错误对象,在您的情况下,如果它不是null 可能会告诉异步您有错误并且不要继续
  • 哈! @JasonSperske 你是对的!
  • 这是我将评论转化为答案的最快速度:)

标签: javascript async.js


【解决方案1】:

由于您使用caolan/async,第一个参数是错误对象,在您的情况下,如果它不是空值,可能会告诉异步您有错误并且不继续。这是文档中的一个示例:

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

【讨论】:

  • 那很快。还有一个问题:现在我在 insertDocument 的回调行上收到“TypeError:object is not a function”,它看起来像:callback(null); ——为什么?
  • 您可以将insertDocument 函数添加到您的问题中吗?还是 function(waterfallCb) {console.log("Step2");insertDocument(null,db,waterfallCb);} 内部发生了 TypeError?
  • 它告诉我错误发生在瀑布中第二个函数的最后一行。所以比如说insertDocument的最后一行(回调行)。
  • 啊,别忘了更新你传递给async.waterfall()的匿名函数的参数签名
  • 请您详细说明一下?
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多