Javascript - 在Websocket上使用Promise? [英] Javascript - Using Promises on Websocket?
问题描述
我在纯Javascript中使用Websockets,我想在Websocket函数中实现Promises。我没有得到任何错误,但Promise不起作用。
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.
使用以下代码我可以成功连接到socketserver但是Promise似乎被跳过,因为警报的输出总是失败。
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".
有人知道这种情况下的问题是什么吗?
Ps:我在最新的谷歌Chrome浏览器和最新的Mozilla Firefox浏览器中进行了测试,我省略了一些基本的检查/错误处理。
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');
});
}
推荐答案
您尝试使用承诺新的连接似乎有点误导。您将需要从 connect()
返回承诺,以便您可以使用它来了解服务器何时连接。
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
});
或使用 async / await
,如下所示:
async myMethod() {
try {
let server = await connect()
// ... use server
} catch (error) {
console.log("ooops ", error)
}
}
这篇关于Javascript - 在Websocket上使用Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!