2015-12-04 82 views
1

嘗試在WebSocket API上實現Promise包裝器。並在Chrome上進行測試。WebSocket和JavaScript承諾

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(); 
}; 

然而,當我運行這個,我在

 var this.socket = new WebSocket(url); 

得到的異常與錯誤

"Pause on promise rejection. TyperError: Cannot set property 'socket' of undefined"

。並在控制檯上看到以下錯誤 -

"Uncaught (in promise) TypeError: Cannot set property 'socket' of undefined".

這裏有什麼問題? Promise對象中引用'socket'變量的「this.socket」是否?如果是這樣,我如何訪問WSConnection對象中的'套接字'變量。有沒有更好的方法來在瀏覽器上提供websocket apis?

+0

嘛'this'在承諾解析器回調不確定的。 – Bergi

+0

我從上面提供的[重複鏈接](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback)中得到了有用的信息。不知道如何接受它。 – sthustfo

+0

當你的問題關閉時,你不需要接受任何東西。你應該提供有用的答案。 – Bergi

回答

1

與錯誤的代碼行是不正確的語法

this.socket = new WebSocket(url);

應該this.socket = new WebSocket(url);我想

new Promise

而且回調的,這將不確定的,因爲它是anonymus回調。

您可以bind這個回調或ES2015箭頭功能(更多詳情here

例如用箭頭功能:

function WSConnection() { 
    'use strict'; 
    this.socket = {}; 
} 

WSConnection.prototype.connect = function (url) { 
    'use strict'; 

    return new Promise((resolve, reject) => { 
     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(); 
}; 
+0

感謝您指出問題。然而,截至目前,只有firefox支持箭頭功能,我猜 – sthustfo

+0

@sthustfo你可以使用轉譯器將其轉換爲ES5(如babel) – yash