问题描述
|
JavaScript与Ruby \的Array#compact等效吗?
长版....我按照blog.nemikor.com上的示例进行操作。他的最后一个示例关闭了旧请求,但是but0ѭ继续被过时的请求填充。对我来说,这似乎是内存泄漏。
我的解决方案是如下对
filter
遍历pendings
,但似乎在pendings.push
和pendings = pendings.filter
之间可能存在竞争条件。我是偏执狂吗?如果存在比赛条件,我该如何解决?
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);
解决方法
您在JavaScript中没有线程,因此不存在竞争条件。所有代码都是经过排序的,只有在完成运行后才能转移控制权。因此,您的间隔功能将一直运行到完成,然后其他任何功能都将触碰
pendings
。
这适用于setTimeout
和setInterval
。
作为实验:如果您使用setTimeout
进行超时,则在1秒后触发。然后,您编写了一个阻塞2秒钟的while循环,那么超时将在此后触发,时间长于1秒。
粗糙的东西:
var timer = setTimeout(function () {
alert(\"hi!\");
},1000);
var now = new Date();
var till = new Date(now + 2);
while(new Date() < till) {} // block for 2 seconds
, 您可能想看看Underscore.js库
http://documentcloud.github.com/underscore/
这提供了许多有用的低级函数来处理集合,数组和对象。它既包含compact
函数(尽管我认为它的功能与您所寻找的目的不同),还包含filter
函数。
, 只要您不执行I / O(即仅执行内存操作),就可以确保不会被中断(由于事件循环的性质)。
如此,请小心,如果您的集合太长(例如成千上万个或更多),因为您可以在一段时间内阻止事件循环,而不用为其他请求提供服务。