为什么这个函数不会返回结果?

时间:2012-07-10 15:18:12

标签: node.js mongodb express

我正在编写自己的类来管理快速框架中的mongodb查询。

这个类看起来像

var PostModel = function(){};

PostModel.prototype.index = function(db){
  db.open(function(err,db){
    if(!err){

      db.collection('post',function(err,collection){

        collection.find().toArray(function(err,posts){
          if(!err){
            db.close();
            return posts;
          }
        });  
      });
    }
  });
};

当我调用此函数时:

// GET /post index action
app.get('/post',function(req,res){

  postModel = new PostModel();
  var posts = postModel.index(db);
  res.json(posts); 

});

我不知道为什么函数索引似乎没有返回任何内容。

但是如果我改变像这样的索引函数

var PostModel = function(){};

PostModel.prototype.index = function(db){
  db.open(function(err,db){
    if(!err){

      db.collection('post',function(err,collection){

        collection.find().toArray(function(err,posts){
          if(!err){
            db.close();
            console.log(posts);
          }
        });  
      });
    }
  });
};

注意console.log而不是return。通过这些更改,我可以在终端中看到我想要的所有帖子。这是因为该功能可以回复所有帖子。

问题是它没有返回帖子:(

1 个答案:

答案 0 :(得分:4)

你正在使用异步功能,它们都会得到回调,所以你也需要使用回调:

var PostModel = function(){};

PostModel.prototype.index = function(db, callback){
  db.open(function(err,db){
    if(!err){

      db.collection('post',function(err,collection){

        collection.find().toArray(function(err,posts){
          if(!err){
            db.close();
            callback(posts);
          }
        });  
      });
    }
  });
};
相关问题