gpt4 book ai didi

javascript - 在 JavaScript 中压缩数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:26 32 4
gpt4 key购买 nike

什么是 JavaScript 等同于 Ruby 的 Array#compact?

长版....我遵循了blog.nemikor.com的例子.他的最后一个示例关闭了旧请求,但是 pendings 继续被过时的请求填充。这对我来说像是内存泄漏。

我的解决方案是使用 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 之前运行直到完成。

这适用于 setTimeoutsetInterval

作为一个实验:如果您使用 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

关于javascript - 在 JavaScript 中压缩数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6181548/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com