Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  106] [ 1]  / answers: 1 / hits: 45047  / 7 Years ago, fri, february 17, 2017, 12:00:00

I am using Websockets in pure Javascript and I want to implement Promises into the Websocket functions. I don't get any errors but the Promise doesn't work.



Using the following code I can connect succesful to the socketserver but the Promise seems to be skipped because the output of the alert is always failed.



Does somebody knows what the problem is in this case?
Ps: I did the tests in the latest Google Chrome browser and the latest Mozilla Firefox browser, and I left out some basic checking/error handling for this example.



function Connect()
{
server = new WebSocket('mysite:1234');

server.onopen = (function()
{
return new Promise(function(resolve, reject)
{
if (true)
{
resolve();
}
else
{
reject();
}
});
}).then = (function()
{
alert('succeeed');
}).catch = (function()
{
alert('failed');
});
}

More From » websocket

 Answers
15

Your attempt to use promises with the new connection seems a bit misguided. You will want to return a promise from connect() so you can use it to know when the server is connected.



It seems like you probably want something like this:



function connect() {
return new Promise(function(resolve, reject) {
var server = new WebSocket('ws://mysite:1234');
server.onopen = function() {
resolve(server);
};
server.onerror = function(err) {
reject(err);
};

});
}


Then, you would use it like this:



connect().then(function(server) {
// server is ready here
}).catch(function(err) {
// error here
});


or with async/await like this:



async myMethod() {
try {
let server = await connect()
// ... use server
} catch (error) {
console.log(ooops , error)
}
}

[#58891] Thursday, February 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaia

Total Points: 574
Total Questions: 109
Total Answers: 110

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
kaia questions
Wed, Mar 17, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Mon, Dec 28, 20, 00:00, 4 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
;