gpt4 book ai didi

Node.js EventEmitter - 糟糕的事情正在发生

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:46 25 4
gpt4 key购买 nike

我一直在尝试解决 Node.js 应用程序中的错误,并将其范围缩小到我实现事件发射器的方式。该应用程序是一个express.js应用程序,具有使用类。我必须忽略 NodeJS 的一些关键方面,即内存使用和类/对象生命周期。我希望有人能指出为什么我所做的事情没有按预期进行。

代码如下:

// ServiceWrapper.js:
var events = require('events');

var ServiceClient = function(opts) {
this.foobar = "";
this.opts = opts;
this.hasFoo = false, this.hasBar = false;
}

ServiceClient.prototype = new events.EventEmitter();

ServiceClient.prototype.getFoo = function() {
var self = this;
self.hasFoo = true;
self.foobar += "foo";
self.emit('done','foo');
}

ServiceClient.prototype.getBar = function() {
var self = this;
self.hasBar = true;
self.foobar += "bar";
self.emit('done','bar');
}

var ServiceWrapper = function(){}

ServiceWrapper.prototype.getResponse = function(options, callback) {
var servClient = new ServiceClient({});
servClient.on('done', function(what) {
if (servClient.hasFoo && servClient.hasBar) {
console.log("foo && bar")
callback(servClient.foobar);
}
else {
console.log("Don't have everything: " + servClient.foobar);
}
});

servClient.getFoo();
servClient.getBar();
}

module.exports = ServiceWrapper

然后在我的 Express 应用程序中:

var ServiceWrapper = require('ServiceWrapper');

app.get('/serviceReponse', function(req,res) {
var servWrapper = new ServiceWrapper();
servWrapper.getResponse(function(ret) {
res.end(ret);
});
});

网络应用程序上的行为按预期工作:响应设置为“foobar”。但是,查看日志,似乎存在内存泄漏 - servWrapper 的多个实例。启动应用程序后,第一个请求生成:

Don't have everything: foo
foo && bar

但是,如果我刷新页面,我会看到以下内容:

foo && bar
Don't have everything: foo
foo && bar
foo && bar

每次刷新时,监听器都会检测到多个“完成”事件 - foo && bar 输出不断增长(假设内存中存在越来越多的 ServiceWrapper 实例)。

为什么会发生这种情况? (我希望看到每个请求的第一个请求得到的输出)。

最佳答案

感谢 freenode 上 #node.js 上的人员对此提供的协助:

sure, but every time you attach listeners, you're attaching them to the same emitter since you didn't localize the prototype's state to your instance, the prototype methods act upon the state of the prototype object. I believe you can fix it by simply doing EventEmitter.call(this) in the constructor

请参阅以下链接了解更多信息:

关于Node.js EventEmitter - 糟糕的事情正在发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20119819/

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