0

So trying to follow this answer here for setting up Socket.io to work in express app with /wwww file and index.js as router. (Ref: Using socket.io in Express 4 and express-generator's /bin/www)

ISSUE: 1) I can connect to the socket out of router.post. however when I try to create a connection inside of router.post to pass results to the client from the server - I can't connect.

  1. I can't send async data via socket.io

Console

a user connected index outside routerrr

Index.js

module.exports = function(io) {

  io.on('connection', function(socket){
    console.log('a user connected index outside routerrr');
  });
  /* GET home page. */
  router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
  });

  router.post('/', async (req, res) => {
      // Assign first query
      searchedT = req.body.searchTerm;
      queries.push(req.body.searchTerm);
      // Invoke the async iterator
      console.log("start....");

      const results = await queryIterator(queries, async function(result) {
        console.log("--->" + await result);
     
         // Trying to connect to socket and send async data!!!!        
        io.on('connection', function(socket) {
          console.log('a user connected inside routerrr');

          socket.on('sentiment result', async function(result){
            io.emit('sentiment result', await result);
          });
        });
  
        // res.send(await result);

      });
      // res.send(result);
  });

    return router;
}

script.js

 var socket = io();

function sendForm() {
    let form = $('#message-entry');
    let query = form.serialize();
    $.post('/', query, async function (data) {
        const results = await data;
        $(function () {
            // var socket = io();
 
            socket.on('sentiment result', function(result){
              $('#sentimentScore').text(result.sentimentResults.sentiment.score);
            });
          });

     });
}
Community
  • 1
  • 1
Shaz
  • 1,443
  • 1
  • 27
  • 67
  • this might help. https://stackoverflow.com/questions/47035243/with-socketio-is-it-possible-to-use-async-with-socket-on – Atishay Jain Oct 09 '18 at 07:37
  • I guess that the `io.on('connection',..` event already has passed at the moment that someone triggers the POST method. And so everything inside the listener will not be called. Try to connect and listen to events outside of the POST callback so that you only have to call `io.emit(...)` inside the POST callback. – cwouter Oct 09 '18 at 07:45

0 Answers0