Tony Roczz
Tony Roczz

Reputation: 2398

How to trigger function from javascript websocket

I am new to websocket. I am currently listening to a websocket in my node.js middleware application. Once I receive a message I have to store that message on database.

const ws = new WebSocket("ws://localhost:3000");

ws.on("message", (event) => {
  console.log("connected to DB");
  testConnection();
});

Whenever a new message is received the testConnection function should be triggered.

async function testConnection() {
  await sequelize.authenticate().then(() => {
    console.log("Connected to DB");
   })
   .catch((err) => {
    console.log(err);
  });
};

I am trying to test connection for now.

But whenever a new message is received the testConnection function is not getting called.

I would like to know how to call a function when receiving a new message.

Upvotes: 0

Views: 1077

Answers (1)

Jonathan Newton
Jonathan Newton

Reputation: 830

You should check out the Websockets docs the message handlers is a callback on the websocket onmessage calling on will just return undefined.

const ws = new WebSocket("ws://localhost:3000");

ws.onmessage = (event) => {
  console.log("connected to DB");
  testConnection();
};


async function testConnection() {
  await sequelize.authenticate().then(() => {
    console.log("Connected to DB");
   })
   .catch((err) => {
    console.log(err);
  });
};

Upvotes: 2

Related Questions