0

That's my problem, I have this function

function getStuff(query){
T.get('search/tweets', { q: query, count: 100 }, function(err, data, response) {
  return data;
})
}

called inside a socket connection

net.createServer(function(sock) {
        sock.on('data', function(data) {

        var tweets = getStuff(request.query); <-- ERROR
        sock.write(JSON.stringify(tweets));    

    });


}).listen(PORT, HOST);

My problem is that the variable tweets doesn't contains anything due to the async connection typical of node js. I'm started to study node js some days ago but for now I can't figure out how can I solve this problem. This is a typical programming pattern but how can I deal with this pattern in node js?

/* UPDATE */

function getStuff(query,callback){
T.get('search/tweets', { q: query, count: 100 }, function(err, data, response) {
  callback(data);
})
}

called in this way

  getStuff(request.query, function(tweets){
    //Getting results
    sock.write(JSON.stringify(tweets));
    }
  );
Usi Usi
  • 2,967
  • 5
  • 38
  • 69
  • *"how can I deal with this pattern in node js"* Callbacks. The same thing you do with `sock.on(...)`. – Felix Kling Jul 03 '14 at 15:16
  • Sure felix but I can't understand how can I do that in this example. – Usi Usi Jul 03 '14 at 15:20
  • Give the `getStuff` function a callback parameter. Have you tried it? show us your attempt (and we'll reopen the question). – Bergi Jul 03 '14 at 15:26
  • Make getStuff accept a function. Pass that function to T.get instead of your own (or call it inside your own, make sure you pass data to it). Pass a function to getStuff and call sock.write in it (the data will be passed as argument to it). I'm sure there are many tutorials which explain how callback work. Either way, this is one of the most important things to learn when you work in Node.js (JS in general, but node.js specifically) – Felix Kling Jul 03 '14 at 15:27
  • Thanks Felix I think that I understand, I've updated the code with my solution. Is this the correct way to solve out my problem or there is a better one? thanks for your patience. – Usi Usi Jul 03 '14 at 15:34
  • If it works it's good ;) If not, there is probably a better solution. Eventually you might want to look into "promises": http://www.html5rocks.com/en/tutorials/es6/promises/ – Felix Kling Jul 03 '14 at 16:27

0 Answers0