Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Waiting for an event in Node.js

Waiting for an event in Node.js

Problem

I have been playing with Node.js for some time.

I have the following piece of script in my server:

socket.on('auth', function(uid, key) {
    client.hgetall(uid, function (err, data) {
        console.log(data);
        if(key != data['key']) {
            socket.disconnect();
        }
        this.user = data;
    });
});

socket.on('loginGame', function(gameId) {
    checkAuth();
    console.log(user);

    if(!games[gameId]) {
        games[gameId] = {};
    }

    games[gameId][uid] = uid;
});

In my client;

socket.on('connect', function(){
    socket.emit('auth', 1, 1);
    socket.emit('loginGame', 1);        
});

When I run this code, loginGame Function finishes before auth function as I am doing I/O (using redis). I know this a feature of node.js, but I think I am missing something. How can I overcome this issue as auth function needs to finish before running any function. (I have a couple of more functions which need to run in serial)

I have found a node.js module: https://github.com/creationix/step . However, is this the only option? I think this is something most node.js developer might need. I am not that good at JS either.

What is the best and most elegant way of solving this issue?

Thanks,

Problem courtesy of: Merinn

Solution

Have the server send back an acknowledgement when auth is successful, and send loginGame in the handler for that message.

Solution courtesy of: Chuck

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Waiting for an event in Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×