I’m trying to use WebSockets for the first time, and I’m making a todo list app. I’m using Express and Socket.io and Redis.
In the following code, socket.emit(‘items’, {items: redisItems}) is failing, saying that emit can’t be done on undefined. I know that client.hgetall is an asynchronous call and that I have to somehow get it to execute the after. How do I fix it? Do I use something like Futures or can this be done with a small fix on what I have right now?
io.sockets.on('connection', function (socket) {
socket.on('getItems', function (socket){
var redisItems = new Array;
callback = function(err,obj){
for ( att in obj) {
item = new Object();
item.key = att;
item.done = obj[att];
redisItems.push(item);
console.log(redisItems.length);
console.log(item.key);
}
socket.emit('items', {items: redisItems})
};
client.hgetall("items", callback);
});
});
Sidenote: What I currently have goes like this: 1) browser requests page 2) Once the browser has the page, it connects through WebSocket and asks for the todo items (so 2 requests).
In the future, I would prefer something like 1) browser makes request for page 2) server gives page and sends items once it’s done.
You’re overwriting your socket object in the
getItemscallback. While the initialio.socketsconnection event returns thesocket, subsequentsocket.onevents don’t return anothersocketobject, they return data for the event. Try something like: