cursor.toArray(callback)不会返回文档数组

我想返回包含甲板集合文档的数组。 我可以让光标指向这些文档,然后使用toArray()函数将它们转换为数组。

问题是我不能返回转换的数组…请看看我的代码。

exports.find_by_category = function (category_id){ var results = []; //Array where all my results will be console.log('Retrieving decks of category: ' + category_id); mongo.database.collection('decks', function(err, collection) { collection.find({'category_id': category_id}).toArray(function(err,items){ results = items; //Items is an array of the documents }); }); return results; //The problems is here, results seems to be empty... }; 

我真的不知道发生了什么,因为results是在外部的范围。 我究竟做错了什么? 我怎样才能实现返回results作为一个发现文件的数组。

正如@Pointy指出的那样,在return results之前,行return results是同步执行的。

解决这个问题的方法是给函数提供一个callback,如下所示:

 exports.find_by_category = function (category_id, callback){ //Notice second param here mongo.database.collection('decks', function(err, collection) { collection.find({'category_id': category_id}).toArray(function(err,items){ if(err) callback(err); else callback(null, items); }); }); }; 

为了更好地理解callback是如何工作的,请查看这个答案 。 是的,asynchronous编程起初很难,而且需要一些习惯。