Search code examples
javascriptwebsocketes6-promise

Javascript - Build an async interface around an async WebSocket


I'm wondering if it is possible to build an async interface around a webSocket object, that is async by nature.

The webSockect object is inside a class/function that publishes a number of methods: I'd like to call this methods, send a command via websocket, wait the reply and recall the standard methods as .then or .catch - thinking like a javascript Promise.

function x() {
    myWS.sendCmdA().then( function() { doSomething; });
}

function myWS(){
  var ws = null;
  this.open = function() {
    ws = new WebSocket(....);
    ws.open = function() { ... };
    ws.onmessage = function () { ... };
  }
  this.sendCmdA = function () {
    ws.send("ABCD");
  }
}

Or it is better to pass a callback function(s) on the call like

myWS.sendCmdA( fnOk, fnErr);

?


Solution

  • This is the final solution I adopted:

    • added two arrays to store the two possible replies

      var _resolved=[];
      var _rejected=[];
      
    • for each request I defined a Promise as following:

        this.ambd002GetLocks = function(locks){
          return new Promise(
            function( resolve, rejected){
                _resolved['ambd002'] = resolve;
                _rejected['ambd002'] = rejected;
                ws.send("{\"parn1\":"+locks+", \"cmd\":\"ambd002GetLocks\"}");
            }
         );
       }
      
    • when I receive the reply on onmessage handler I check the result and recall one of the stored function, using a specified index:

      ws.onmessage = function got_packet(msg) {
                console.info("RxWs: " + msg.data);
      
                ...
                    case "ambd002GetLocks":
                        if (obj.v=="ok"){
                            _resolved['ambd002'](obj);
                        } else {
                            _rejected['ambd002'](obj);
                        }
                        break;
               ...