0

I have a node.js app with websocket

When the user get into '/' I need to send command message (json message) with web socket to other application.

When I get results from the other application, I need to return it.

It seems that I return empty results to the user, and I don't know why

serv.js file:

const websocket = require('ws')
async function sendData(command) {
  const ws = new websocket('ws://127.0.0.1:5678')
  ws.on('open', function open() {
     ws.send(JSON.stringfuly(command))
  });

  ws.on('message', function incoming(data) {
    return data
  });

return {}
}

module.exports = {
  sendData,
}

index.js file:

connection = require('serv');

const router = Router();
.route('/')
.get(async(req, rep) => {
   // fill json command
   command = fillCommand()
   result = await connection.sendData(command)
   res.json(result);
})

I tried to debug, and I can see that results = await connection.sendData(command) get {} result only.

I tried to remove the return {} and I got the same results

I see that I'm getting results from the ws.on('message'... , But it is not get back to index.js

what am I missing and how can I fix it ?

Boom
  • 1,145
  • 18
  • 44
  • _"...and I don't know why"_ - Because that's what you're doing here `return {}` which is the only return in `sendData()`. – Andreas Jul 14 '20 at 10:07
  • You do `return {}`. I am not expert of websocket, but it seems that you should listen for `open` and `message` events instead. – Justinas Jul 14 '20 at 10:07
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) (like `ws.on('message' , ...)`) – Andreas Jul 14 '20 at 10:07

1 Answers1

1

I believe the problem is that you are returning the data inside the listener for the message event, which doesn't return the value from the async function. This kind of conversion from callbacks to promises can only be done with the Promise constructor.

function sendData(command) {
  const ws = new websocket("ws://127.0.0.1:5678");
  ws.on("open", function open() {
    ws.send(JSON.stringfuly(command));
  });

  return new Promise( (res, rej) => {
    ws.on("message", (data) => {
      res(data);
    });

    // Don't forget to handle errors.
    ws.on("error", (error) => {
      rej(error);
    });
  });
}
D. Pardal
  • 6,173
  • 1
  • 17
  • 37