#Await WebSocket response - does my idea make sense?

7 messages · Page 1 of 1 (latest)

potent valve
#

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, ...);
  1. 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.
  2. The server sees that the mesage has special ID, processes the data and when it sends response, it appends the same ID.
  3. 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?

#

Await WebSocket response - does my idea make sense?

raven thorn
#

ws fundamentally doesn't involve the req/res that http uses. if you want that flow, why not use http?

coral lichen
#

socket.emitWithAck even returns a promise :)

potent valve
coral lichen
#

SSE is the worst of both worlds tbf :D