1
app.get('/', function(req, res) {
    res.set('Content-Type', 'text/html');
    res.send('Yo');
    setTimeout(function(){
        res.send("Yo");
    },1000);
});

It looks like "send" ends the request. How can I get this to write Yo on the screen and then 1 second later (sort of like long polling I guess) write the other Yo to get YoYo? Is there some other method other than send?

5 Answers 5

2

Use res.write to generate output in pieces and then complete the response with res.end.

Sign up to request clarification or add additional context in comments.

1 Comment

That would still send the entire response in one shot though, I think what@K2xL is trying to do is send messages separately whenever results become available, so sockets would be the way to go here.
1

I don't think what you are trying to do is possible. Once you send a response, the client-server connection will be closed.

Look into sockets (particularly socket.io) in order to keep a connection open and send multiple messages on it.

Comments

0

Try with JQuery+JSON. send the response and then update what ever you need with JQuery and JSON.

This is a good tutorial of expressjs, including DB stuff (mongodb).

Comments

0

If you want to send the result as a single block try

app.get('/', function(req, res) {
    res.set('Content-Type', 'text/html');
    res.write('Yo');
    setTimeout(function(){
        res.end("Yo");
    },1000);
});

or something like

app.get('/', function(req, res) {
    res.set('Content-Type', 'text/html');
    var str = 'yo';
    setTimeout(function(){
        res.end(str + 'yo');
    },1000);
});

Comments

0

the thing with node.js is that it relies on an asynchronous "style". so if you introduce something like a "wait" function, you'll lose all the benefits of the asynchronous way of execution.

I believe you can achieve something similar to what you want by:

  1. (asynchronous way) including a function that prints the second "Yo" as a callback to the first function (or)
  2. (classic wait(synchronous) ) introduce a 'big' loop before presenting the second 'Yo'.

for example:

for(i=0; i < 100000000; i++) {
    //do something
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.