简体   繁体   中英

socket.io - emitting from within an anonymous function

I am quite new to the world of async. I am trying to do everything with callbacks at first before using any of the libraries out there. I think I have a closure problem, but don't know what to do about it.

Here is some code:

namespace.on('connection', function(socket){
    var newClient = socket.id//just in case the a new user logged on between declaration and use
    socket.join('room1')
    function newConnection(positionCallback, hashCallback, newUser){
        namespace.to(socket.id).emit('hello', {yo:'works'})
        for(var i=0; i< cardCounter ;i++){
            var keyVal = 'card:'+ cardArray[i]
            redis.hgetall(keyVal, function (err, storedMsg) {
                    namespace.to(socket.id).emit('hello', {yo:'doesnt work'})
                    hashCallback(storedMsg, newUser)
                });
            if(i==cardCounter-1){
                positionCallback()
            }
        }
    }

    function onConnectionComplete(){
        namespace.to(socket.id).emit('hello', {yo:'works'})
    }

    function onHashComplete(hashObject, newUser){
        namespace.to(newUser).emit('hello', {yo:'doesnt work'})
    }

    newConnection(onConnectionComplete, onHashComplete, newClient)
}

I have placed some socketio emits around the place to pinpoint where things go wrong.

Any emits outside of the call to redis work as expected. As soon as I go inside that anonymous function - nada.

That said, I have console.log()'ed everything inside that function. I get the right results from redis, I have the right user, and namespace is defined.

I just can't emit the result.

I would have thought that the anonymous function had access to the scope just outside it - but not the other way around. I don't see what is not making it across...

Also I know that some people don't like the if statement to invoke a callback, but that might be a discussion for another day.

It was a closure problem! Just not what I was expecting.

I also, ahem, don't really understand it.

The callback isn't the problem, getting variables accessible inside the redis response function is. I would have thought that any variables declared in a parent/ancestor function are available to children/decedent functions.

In this instance I needed to create a function inside the loop, and explicitly pass variables for it to be available inside a closure.

Here is the stackoverflow question that pointed me in the right direction:

How can I access the key passed to hgetall when using node_redis?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM