What is JavaScript equivalent to Ruby’s Array#compact?
Long version…. I followed the examples at blog.nemikor.com. His last example closes out old requests, but then pendings continues to be filled with obsolete requests. This looks like a memory leak to me.
My solution is to iterate over pendings with filter as below, but this seems like there may be a race condition between pendings.push and pendings = pendings.filter. Am I being paranoid? If a race condition exists, how should I fix it?
var pendings = [];
// there is a route
app.get('/some/path', function (request, response) {
pendings.push({
response: response,
requestedAt: new Date().getTime()
});
});
setInterval(function () {
var expiration = new Date().getTime() - (1000 * 30);
pendings = pendings.filter(function (pending, index) {
if (pending.requestedAt > expiration) {
return true;
} else {
pending.response.writeHead(408, { 'Content-Type': 'text/plain' });
pending.response.end('');
}
});
}, 1000);
You have no threads in JavaScript, so there can be no race condition. All code is sequenced and will transfer control only after it’s done running. So your interval function will run till completion before any other function is going to touch
pendings.This holds for things like
setTimeoutandsetInterval.As an experiment: If you made a timeout using
setTimeoutto fire after 1 second. And after that you write a while-loop that blocks for 2 seconds, your timeout will fire after that, so much longer than 1 second.Something crude: