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:
JavaScript
x
19
19
1
$("#button").click(function () {
2
var exists = false;
3
var name = $("#name").val();
4
socket.emit("check", name);
5
6
socket.on("checkReturn", function (data) {
7
exists = data.result;
8
});
9
10
if (exists) {
11
console.log("exists")
12
} else {
13
if (name.length > 0) {
14
socket.emit("create", name);
15
}
16
}
17
});
18
});
19
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?
Advertisement
Answer
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:
JavaScript
1
11
11
1
$("#button").click(function() {
2
var exists = false;
3
var name = $("#name").val();
4
5
socket.emit('check', name, function (data) {
6
exists = data.result;
7
if (exists) console.log("exists");
8
else (if (name.length > 0) socket.emit("create", name));
9
});
10
});
11
On the server side it would look like this:
JavaScript
1
7
1
io.sockets.on('connection', function (socket) {
2
socket.on('check', function(name, fn) {
3
// find if "name" exists
4
fn({ exists: false });
5
});
6
});
7