I am facing an issue with my websocket connection between the client (browser) and server. Sometimes when I request data through the websocket, I struggle to efficiently manage my code due to its event-based nature.
When I send a websocket message in a function, I then have to listen for and handle it in the event listener. This creates a disconnect between the request and response handling in my code.
For example:
const ws = new WebSocket("ws://whatever");
function handleClickBtn() {
ws.send('request something');
// cannot get response here
}
ws.onmessage = function (event) {
console.log(`response comes here: ${event.data}`);
}
It feels like a challenge to maintain this code structure compared to using REST API with async/await syntax for easier handling of requests and responses. Are there any techniques that could be applied here to improve this situation?