I'm building some software that behind the scenes needs to communicate with hardware via a "message" API, over a named pipe.

For example, I can send this message:

<?xml version="1.0" encoding="UTF-8" ?>
  <bts version="1.0">
    <cmd>getdevinfo</cmd>//Tells the hardware the message type, or command.

Here comes the challenging part: This message doesn't involve any callback. The only way I can get the response from the hardware, is to listen for incoming message events, and check their "cmd"(type).

This is of course problematic, because under certain conditions, multiple responses of this type might be emitted, whose order doesn't correspond the order of the commands sent by the clients.

The corresponding response message of the example above would be something like:

<?xml version="1.0" encoding="UTF-8" ?>
<bts version="1.0">
  <cmd>getdevinfo_resp</cmd>//Here i can check the message type.
  <middle count = “1”>
    <channel ip="" devtype="22" devid="1" subdevid="1" Channelid="1">true</channel>

Bottom line is, I'm looking for some pattern, that would allow me to "safely" combine these two seemingly unrelated events(outgoing message, incoming message) into a single "procedure". In JavaScript terms, it should be wrapped into a promise:

const getdevinfo_resp = await sendMessage('getdevinfo','some XML content...')//Note how the promise is resolved only when the corresponding response message arrives.

Any ideas will be greatly appreciated

1 Answer 1


I am afraid with that setup, you are out of options. Create a singleton instance that has a method that blocks until the reply is received. Anything else will result in weird, hard to track failures.

Now if you had control over the API, you could incorporate something like a requestId, that will be put into the response, too. Then you could build all kind of nice non-blocking, non-singleton things because you know which response belongs to which request. But if you don't have that control over the API, you are screwed and you need to implement it as a bottleneck where only one message goes in until the one reply has come out.

  • Yes, this is my plan, in case i don't find any option of adding an ID, in the hardware API
    – i.brod
    Jan 17, 2022 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.