I am trying to do a project with node.js, but I met a problem displaying a variable.
This part of the code on the client side:
$(document).ready(function () {
var socket = io.connect('http://localhost:8000');
var a = 0;
var b = 0;
socket.on('request', function (data) {
a = data;
});
socket.on('read', function (data) {
b = data;
});
var q = a * b;
$('span#calculate').html(q);
// Etc...
});
Normally it should display the result of this calculation, but it still displays a 0 (that means the variable has not changed in socket.on).
How can I solve this problem?
Welcome to the world of asynchronous code! Where nothing runs linearly.
The code you have there is just adding listeners for events read and request, not actually changing a and b. Therefore, a and b are still 0 until the handlers are executed, which would be when the server sends over the read or request events.
What you can do is to place whatever you want to happen after the events fire in a function. Then call that function in the event handlers:
$(document).ready(function () {
var socket = io.connect('http://localhost:8000');
var a = 0;
var b = 0;
var calculate = $('span#calculate');
function recalculate(q) {
calculate.html(q);
//more...
}
socket.on('request', function (data) {
a = data;
recalculate(a * b);
});
socket.on('read', function (data) {
b = data;
recalculate(a * b);
});
});