使用mongoose和socket.io处理应用程序中的回调

时间:2013-04-29 14:56:55

标签: node.js socket.io mongoose

开始使用带有mongoose ODM的socket.io并解决了这个问题...... 假设我需要从数据库中获取数据(一些文章)

客户代码:

socket.on('connect', function (data) {
  socket.emit('fetch_articles',function(data){       
    data.forEach(function(val,index,arr){
      $('#articlesList').append("<li>"+val.subject+"</li>")
    });
  });
});

和服务器代码:

var article_model = require('./models');

io.sockets.on('connection', function (socket) {
    var articles = {};
    // Here i fetch the data from db
    article_model.fetchArticles().sort('-_id').limit(5).exec(function(err,data){
      articles= data; // callback function
    });

    // and then sending them to the client
    socket.on('fetch_articles', function(fn){
      // Have to set Timeout to wait for the data in articles
      setTimeout(function(){fn(articles)},1000);
    });
});

所以我需要等待回调中应该进入的数据同时执行socket.on回调。

这个问题是否有简单而正确的解决方案?

1 个答案:

答案 0 :(得分:1)

看起来你想要这个:

var articles = null;
socket.on('fetch_articles', function(fn) {
  if (articles) {
    fn(articles);
  } else {
    article_model.fetchArticles().sort('-_id').limit(5).exec(function(err,data) {
      articles = data;
      fn(articles);
    });
  }
});