Handling callbacks in app with mongoose and socket.io

Started using socket.io with mongoose ODM and came to the problem... Suppose i need to fetch data ( some articles) from database

Client code:

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

and Server code:

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);
    });
});

So i need to wait for the data that should come in in callback the same time socket.on callback executed right away.

So is there simple and correct solution to this problem ?

It looks like you want this:

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);
    });
  }
});