I'm using the ws library with node.js. I have a websocket connection between a node.js web app and a browser. I have the browser 'request' data by messaging the web app over the websocket. The web app parses the message to figure out what the browser wants. So if the 'query_name' is 'member_DOB', then the web app will send back the member's date of birth. You get the idea.
To do this, I need to assign the incoming 'query_name' to a variable on my web app. Problem is, if I have more than one message coming in at the same time, the variable is assigned to the first 'query_name' but before the function finishes running, the variable is re-assigned to equal the next incoming message 'query_name'.
How do I link the variable to each individual message coming in and prevent it from changing?
var query_name;
const WebSocket = require('ws');
const wss = new Websocket.Server({server:httpsServer});
ws.on('message', function (data) {
query_name = JSON.parse(data)[0];
// do a whole bunch of stuff with query_name;
}
"A function serves as a closure in JavaScript, and thus creates a scope" https://developer.mozilla.org/en-US/docs/Glossary/Scope.
Hence, define the var or const INSIDE the function, so that it may be tied to that particular instance of the function being called.
const WebSocket = require('ws');
const wss = new Websocket.Server({server:httpsServer});
ws.on('message', function (data) {
const query_name = JSON.parse(data)[0];
// do a whole bunch of stuff with query_name;
}