2012-10-21 25 views
0

我試圖使用Async.js來啓動一系列異步函數。以下是我的代碼。只有前兩個功能執行。系列中的第三和第四個功能不會執行。我已經將思想簡化爲最基本的可能。但他們仍然不執行。有人能告訴我我做錯了什麼嗎?並非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"); 

     } 
    ]); 

回答

4

看看這段代碼,它只輸出1 2 3,因爲3rd函數沒有調用回調函數,所以系列在這裏停止。 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); 
    },         
    ]);​ 
0

集合中的前兩個項目並不像功能,它看起來像你立即調用前兩個功能 - 或不計()返回一個函數?

如果你正在調用它們,而不是將函數傳遞給異步,那就是爲什麼它在獲取最後兩項之前窒息的原因。

+0

不計數只是返回一個整數。我在函數中包裝了前兩項(請參閱編輯),但它不能解決問題。現在只有第一個項目執行。 – hughesdan

1

你應該只提供async.series功能。數組中的第一項不是函數。你需要將這些調用包裝成一個。

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

我試過了(見上面的編輯)。但是,這似乎不是這個代碼中唯一的問題。 – hughesdan

相關問題