Waiting till call back completes Node.js

73 views
Skip to first unread message

Pradeep Simha

unread,
Aug 12, 2014, 10:55:28 PM8/12/14
to nod...@googlegroups.com
My situation is like this, I have a server like this and inside I am calling another callback function which gets multiple values:
    
    var http = require('http'); 
    var server = http.createServer(req,resp) {
         var finalVal = "";
         
         consumer.on('message',function(message) {
             finalVal = message;
             console.log(finalVal);
         });

         resp.end(finalVal);
    });

My finalVal should display all the multiple values it fetches and send it as a response, but problem is it's sending only first value where as console.log displays all the values. I do understand that by the time consumer.on ends response would have committed. Can someone please help me how to handle this scenario since I'm very new to Node.js ? Currently due to heavy deadlines I don't have time to read full information about callbacks. But defnitely I would take time to learn about callbacks.

Here `consumer.on` calls multiple times till it fetches all the data from backend, I need to send all those data in a final response. I am using `node-kafka` to consume to kafka messages.

greelgorke

unread,
Aug 13, 2014, 9:57:59 AM8/13/14
to nod...@googlegroups.com
    var http = require('http'); 
    var server = http.createServer(req,resp) {
         var finalVal = "";
         
         consumer.on('message',function(message) {
             finalVal = message;
             console.log(finalVal);
             if(isRealyTheFinalMessage())
                  resp.end(finalVal);
         });

      
    });

// ravi

unread,
Aug 13, 2014, 5:13:06 PM8/13/14
to nod...@googlegroups.com
On Aug 12, 2014, at 10:55 PM, Pradeep Simha <pradeep...@gmail.com> wrote:
My situation is like this, I have a server like this and inside I am calling another callback function which gets multiple values:
    
    var http = require('http'); 
    var server = http.createServer(req,resp) {
         var finalVal = "";
         
         consumer.on('message',function(message) {
             finalVal = message;
             console.log(finalVal);
         });

         resp.end(finalVal);
    });


Well, you can move the resp.end() inside the function(message) { } block. But if consumer.on() can fire multiple times and you need to accumulate the messages, how do you know when the data is complete? You will need to add a check for that.

—ravi
Reply all
Reply to author
Forward
0 new messages