并非Async.js系列中的每个函数都执行

时间:2012-10-21 23:19:12

标签: javascript node-async

我正在尝试使用Async.js来触发一系列异步函数。以下是我的代码。只执行前两个函数。系列中的第三和第四个函数不执行。我已经将功能思维简化为最基本的功能。但他们仍然没有执行。谁能告诉我我做错了什么?

async.series([
        guessCollection.find( { user: user, imageFileName: imageFileName } ).count( function(err, number) {
        count = number;
        console.log(count);
        }),

        guessCollection.find( { user: user, imageFileName: imageFileName, correct: '1' } ).count( function(err, number) {
        correct = number;
        console.log(correct);
        }),

        function(){
            console.log("this text never doesn't get logged");
        },
        function() {
            console.log("neither does this text");

        }
    ]);

编辑---正如下面的答案所示,我做了前两个正确的功能。但是现在只执行该系列中的第一个函数。函数2-4不被调用。我认为这段代码肯定存在其他问题。

async.series([
        function(){
        guessCollection.find( { user: user, imageFileName: imageFileName } ).count( function(err, number) {
        count = number;
        console.log(count);
        })
    },
        function(){
        guessCollection.find( { user: user, imageFileName: imageFileName, correct: '1' } ).count( function(err, number) {
        correct = number;
        console.log(correct);
        })
    },

        function(){
            console.log("this text never doesn't get logged");

        },
        function() {
            console.log("neither does this text");

        }
    ]);

3 个答案:

答案 0 :(得分:4)

看看这段代码,它只输出1 2 3,因为第3个函数没有调用回调函数,所以系列停在这里。 http://jsfiddle.net/oceog/9PgTS/

​async.series([
    function (c) {
        console.log(1);
        c(null);
    },        
    function (c) {
        console.log(2);
        c(null);
    },        
    function (c) {
        console.log(3);
//        c(null);
    },        
    function (c) {
        console.log(4);
        c(null);
    },        
    ]);​

答案 1 :(得分:1)

您应该只为async.series提供功能。数组中的第一项不是函数。你需要将这些调用包装成一个。

async.series([
  function () {
    collection.find().count(function () { … });
  },
  function () {
    collection.find().count(function () { … });
  },
  function () {
    console.log();
  },
  function () {
    console.log();
  }
]);

答案 2 :(得分:0)

集合中的前两个项看起来不像函数,看起来你正在调用前两个函数 - 或者count()是否返回一个函数?

如果你正在调用它们,并且没有将函数传递给异步,那就是为什么它在到达最后两个项目之前会窒息。