With AJAX we can await response data.
const response = await fetch(...);
With WebSockets we can't, because send returns undefined.
ws.send(...);
This makes total sense, but I feel like it would be nice to have an optional feature that would allow us to pause current function and await response.
So what if I would create a wrapper:
const response = await sendWithResponse(ws, ...);
- Wrapper generates a unique ID and creates a Promise. They're stored in a Map. The ID is appended to the data that we're sending. Finally we return the Promise that could be awaited.
- The server sees that the mesage has special ID, processes the data and when it sends response, it appends the same ID.
- Back on the client when we receive a message from a server, we see that it has special ID, search for it in the Map and if we found it, we resolve the promise with the response data.
And we could add setTimeout to terminate response in X seconds so in case something goes wrong we wouldn't wait forever.
Does this make sense? Is a decent idea or am I overcomplicating things?