Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io with promise or async callbacks

This might be kind of an anti pattern, but what would be the best way to simulate a a promise callback when emitting data from client to server using socket.io?

For some event I would very much like it to behave like a normal get request so the client send data to the server and the server could reply with a response and then resolve or reject the promise.

like image 453
Johan Nordberg Avatar asked Feb 19 '26 10:02

Johan Nordberg


1 Answers

Here's what I did. I created a function that emits a socket command, and then returns a promise. My one caveat is I haven't done a lot with this code yet, so it might need some tweaking. It also requires Q for its promises/deferreds.

Client function definition:

var EmitPromise = function( socket, command, data ) {

    var deferred = Q.defer();

    socket.emit(command, data, function( response ) {

        if( typeof response === "object" ) {

            if( response.success === true ) {

                deferred.resolve(response.data);

            } else {
                if( typeof response.message === "string" ) {
                    deferred.reject( response.message );
                } else {
                    deferred.reject( "The request was not successful." )
                }
            }
        } else {

            deferred.reject( "The response to your request could not be parsed." );
        }

    });

    return deferred.promise.timeout( 30000, "The request took too long to respond." );
}

Client side code to make the call:

EmitPromise( socket, "getValue", "username" )
.then(
    function( data ) {

        console.log(data);
        return EmitPromise( socket, "getValue", "anotherValue" );

    }, function( message ) {
        console.log(message);
    }
).then(
    //Chain your commands from here
);

Server side handler

The most important part of this handler is that the second parameter, here named setValueResult must be called with an object that contains a "success" key that holds a true or false value. This was a decision on my part to provide a way to reject the promise in case of some kind of error on the server side.

socket.on( 'getValue', function( valueName, setValueResult ) {

    var value = getValue(valueName) //Do something with value here

    if( value ) {
        setValueResult({
            success : success,
            data : value
        });
    } else {
        setValueResult({
            success : success
            message : "Unable to retrieve value"
        });
    }
}
like image 118
Greg Tatum Avatar answered Feb 20 '26 22:02

Greg Tatum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!