带有promise或异步回调的Socket.io

Joh*_*erg 3 javascript node.js socket.io

这可能是一种反模式,但是promise callback在使用客户端向服务器发送数据时模拟aa的最佳方法是socket.io什么?

对于某些事件,我非常希望它表现得像普通的get请求,因此客户端将数据发送到服务器,服务器可以回复响应,然后解析或拒绝承诺.

Gre*_*tum 6

这就是我做的.我创建了一个发出socket命令的函数,然后返回一个promise.我的一个警告是我还没有完成这个代码,所以可能需要一些调整.它还要求Q承诺/延期.

客户端功能定义:

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." );
}
Run Code Online (Sandbox Code Playgroud)

拨打电话的客户端代码:

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
);
Run Code Online (Sandbox Code Playgroud)

服务器端处理程序

此处理程序最重要的部分是第二个参数,此处名为setValueResult,必须使用包含"success"键的对象调用,该键包含true或false值.这是我决定在服务器端出现某种错误时提供拒绝承诺的方法.

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"
        });
    }
}
Run Code Online (Sandbox Code Playgroud)