socket.io - socket.on 等待承诺 [英] socket.io - socket.on wait for promise
问题描述
我有一个按钮可以与服务器进行一些通信,以检查输入的值(通过输入框)是否已经存在.代码如下:
I have a button that does some communication with the server to check if an entered value (via an input box) already exists. The code is the following:
$("#button").click(function () {
var exists = false;
var name = $("#name").val();
socket.emit("check", name);
socket.on("checkReturn", function (data) {
exists = data.result;
});
if (exists) {
console.log("exists")
} else {
if (name.length > 0) {
socket.emit("create", name);
}
}
});
});
问题在于 checkReturn
调用是异步的,因此代码无需等待结果即可继续执行.我如何确保 checkReturn
首先完成,然后才执行其余代码?
The problem is that the checkReturn
call is asynchronous, and therefore the code carries on without actually waiting for the result. How do I make sure that checkReturn
is first finished and only then the rest of the code gets executed?
推荐答案
除了其他答案之外,您还可以使用确认,即在客户端和服务器之间传递回调.然后就可以直接使用emit函数的回调了:
Aside from the other answer, you can also use acknowledgements, where a callback is passed between the client and server. Then you can just use the callback of the emit function:
$("#button").click(function() {
var exists = false;
var name = $("#name").val();
socket.emit('check', name, function (data) {
exists = data.result;
if (exists) console.log("exists");
else (if (name.length > 0) socket.emit("create", name));
});
});
在服务器端,它看起来像这样:
On the server side it would look like this:
io.sockets.on('connection', function (socket) {
socket.on('ferret', function(name, fn) {
// find if "name" exists
fn({ exists: false });
});
});
这篇关于socket.io - socket.on 等待承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!