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); } } }); });
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:
$("#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('check', function(name, fn) { // find if "name" exists fn({ exists: false }); }); });