[英]Handling callbacks in app with mongoose and socket.io
開始將socket.io與貓鼬ODM一起使用並出現問題...假設我需要從數據庫中獲取數據(一些文章)
客戶代碼:
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回調。
那么,有沒有簡單而正確的解決方案來解決這個問題?
看起來您想要這樣:
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);
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.