I am writing a Koa middleware that, on each request to the server, analyzes some input from a file on the server, and sends it over the websocket (using https://www.npmjs.com/package/ws) to the client.
This all works as expected, except for one problem. The data (as a result of analyzing the input from the file) updates properly, but doesn't update inside the websocket callback scope.
const websocket = new WebSocket.Server({ port: 8082 });
const sourceAST = parseJS();
const conditionResults = getConditionResults(sourceAST);
console.log('handling request', conditionResults); // <-- updates as expected every time
websocket.on('connection', ws => {
console.log(conditionResults); // <-- not updated :(
ws.send(
JSON.stringify({
type: 'feedback-updated',
feedback: conditionResults,
}),
);
});
I can't seem to figure out why the conditionResults inside the ws callbacks is frozen on the first time it is ran, why it doesn't update each time this code is ran (on every request).
Edit: for context, the code snippet above lives inside a middleware function like this:
myMiddleware = async (ctx, next) => {
await next();
// my code snippet above
}
And the middleware is ran in Koa like so:
app.use(myMiddleware);