murid murid - 6 months ago 9
Node.js Question

How do I socket.emit() data that is coming from a function?

Node.js - Socket.io

I can pass data from the server to the client just fine if that's a string or a hard-coded variable:

var greeting = 'hello';
socket.emit('greeting', greeting);


But when the data comes from a function, that doesn't work anymore:

function search() {
var greeting = 'hello';
}
search();
socket.emit('greeting', greeting);


Edit:

Let me share more code: (Please note that console.log of results works, shows the JSON data, but emit shows null).

io.sockets.on('connection', function (socket) {
socket.on('user location', function(content) {
fetch();
socket.emit('results', fetch());
});
});

function fetch() {
yelp.search({term: "food", location: location, limit: 1}, function(error, data) {
var results = data.businesses;
console.log(results); // THIS WORKS
return results;
});
}

Answer

do this:-

io.sockets.on('connection', function (socket) {
  socket.on('user location', function(content) {
    fetch(function(data){
        socket.emit('results', data);
    });
  });
});

function fetch(callback) {
  yelp.search({term: "food", location: location, limit: 1}, function(error, data) {
    var results = data.businesses;
    console.log(results); // THIS WORKS
    callback(results);
  });
}