2015-11-19 42 views
0

我一直指向使用async模塊,但我不太清楚如何使用瀑布來解決我的問題。異步陣列問題

我原來的代碼有異步問題。

 var Image = require('./models/image'); 
     var User  = require('./models/user'); 

     var query = Image.find({}); 

     query.limit(10); 
     query.sort('-date') 

     query.exec(function (err, collected) { 
      if (err) return console.error(err); 
      var i = 0; 
      var authors = []; 

      while (i < 8) { 
       var search = User.find({'twitter.id' : collected[i].author}); 


       search.exec(function (err, user){ 
        if (err) return console.error(err); 

        var result = (user[0].twitter.username); 
        authors.push(result); 
       }); 

       i = i + 1; 
      } 
     } 

     console.log(authors); 

我想作者數組保存所有找到的用戶名。但是,當最後一個console.log()調用返回'[]'

回答

1

因此,您想要等待全部首先完成搜索。您應該將所有異步調用放入數組中,然後使用異步庫將它們鏈接在一起(瀑布)或同時執行(並行)。並行往往執行「更快」:

var searches = []; 
while (i < 8) { 
    var search = User.find({'twitter.id' : collected[i].author}); 
    searches.push(function(cb) { 
     search.exec(function (err, user){ 
      if (err) cb(err, null); 
      else cb(null, user[0].twitter.username); 
     }); 
    }); 
    i++; 
} 
async.parallel(searches, function(err, authors) { 
    if (err) return console.error(err); 
    console.log(authors); 
    // Authors only defined here. 
    // TODO: More code 
}); 
// Authors not defined here. 
+0

哦,好吧,太棒了。 exec函數中的cb是什麼? –

+0

這是回調函數,讓異步庫知道它已完成。你可以在這裏閱讀更多:https://github.com/caolan/async#parallel – TbWill4321

+0

我不知道我是否犯了一個小錯誤。我的代碼拋出'cb沒有定義'的錯誤,但我假設它不是我定義的東西,而是已經在async模塊中定義的(假設它具有特定行爲,帶有錯誤和結果數組)。 –