Trying to implement a promises wrapper on top of WebSocket api. And testing on chrome.
function WSConnection() {
'use strict';
this.socket = {};
}
WSConnection.prototype.connect = function (url) {
'use strict';
return new Promise(function (resolve, reject) {
var this.socket = new WebSocket(url);
this.socket.onopen = function () {
socket.send('hello from the client');
resolve();
};
this.socket.onmessage = function (message) {
console.log("Received on websocket: " + message);
};
socket.onerror = function (error) {
console.log('WebSocket error: ' + error);
reject(error);
};
socket.onclose = function (event) {
console.log("Websocket socket closed: " + JSON.stringify(event));
};
});
};
WSConnection.prototype.disconnect = function () {
'use strict';
console.log("Disconnect request from local app layer");
this.socket.close();
};
However when I run this, I get exception at
var this.socket = new WebSocket(url);
With the error
"Pause on promise rejection. TyperError: Cannot set property 'socket' of undefined"
. And on the console I see following error -
"Uncaught (in promise) TypeError: Cannot set property 'socket' of undefined".
What is wrong here? Does "this.socket
" referring to 'socket' variable in promises object? If so, how can I access the 'socket' variable in the WSConnection object. Is there a better way to promisify websocket apis on the browser?