Lauro’s answer is correct, but his code will not work precisely by while (true)
.
To create an asynchronous loop, you can use recursion with setTimeout:
let app = require('express')();
let responses = []
app.get('/', (req, res) => {
// o res.count que eu criei serve apenas para finalizar
// o chamado depois de 5 iterações
// dessa forma da pra testar pelo navegador, que só mostra
// a resposta quando o pedido for finalizado
res.count = 0;
responses.push(res)
});
app.listen(2000);
// função recursiva
function responder() {
// 'programa' uma função para ser executada daqui a 1000 ms
setTimeout(() => {
responses.filter(res => !res.finished).forEach(res => {
res.count++;
res.write('Cadeia de bytes aqui');
// a partir de agora o res.finished será true
if (res.count === 5) res.end();
});
// quando finalizar a função, chama responder novamente
responder();
}, 1000);
}
// inicializa o loop
responder();
Remember that javascript runs on only one core. Asynchronous functions do not run on different cores, but on the main core as well as the rest of your code. The difference is that asynchronous functions are executed after all their synchronous code is executed.
Hence the while (true)
prevents any other asynchronous code from being executed: it is synchronous and infinite.
Acredtio que while (true) would stop the server from working. But anyway, res.finished really is a valid option, and I think req.complete too.
– Julio Hintze
@Juliocesarhintzedossantos, I hope that
while
be just example. I don’t know where you found your reference (req.complete), would be of http.Incomingmessage and your messages ... if this is the case I think it does not serve the question because it only deals with the answershttp.ServerResponse
– Lauro Moraes
I think you’re right. Maybe my comment is not pertinent (and not recommended in this case) to follow, as I did not take req.complete from any documentation, but from a test I did on my computer (after the request is answered, the object gains a property called "complete" with the value true).
– Julio Hintze
@Lauromoraes I tested with the
res.finished
and it didn’t work, it can’t identify that the connection was terminated.– Lucas Caresia