Javascript - 在 Websocket 上使用承诺? [英] 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:我在最新的 Google 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');
});
}
推荐答案
您尝试在新连接中使用 Promise 似乎有点误导.您将希望从 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 上使用承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!