Node.js 使用mongoose和socket.io处理应用程序中的回调
开始在mongoose ODM中使用socket.io并解决了问题。。。 假设我需要从数据库中获取数据(一些文章) 客户端代码:Node.js 使用mongoose和socket.io处理应用程序中的回调,node.js,socket.io,mongoose,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.s
socket.on('connect', function (data) {
socket.emit('fetch_articles',function(data){
data.forEach(function(val,index,arr){
$('#articlesList').append("<li>"+val.subject+"</li>")
});
});
});
因此,我需要等待回调中的数据与socket.on回调立即执行的时间相同
那么,这个问题有没有简单正确的解决方案?看起来您想要的是:
完成后,它将查询结果保存在
文章中
,并将其重新用于后续请求。
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);
});
});
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);
});
}
});