2013-04-29 57 views
0

使用帶貓鼬ODM socket.io啓動,來到了問題... 想我需要獲取從數據庫中的數據(一些文章)在應用程序處理回調與貓鼬和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

它看起來像你想的:

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

我想是...在文章變量,然後沒有必要...感謝 – Roman 2013-04-29 16:15:05

+0

這樣可以節省當它完成查詢的'articles'的結果,並將其重用於隨後的請求。 – robertklep 2013-04-29 17:46:34