[英]Nodejs - promises, unhandled termination and memory leak
seeking help from nodejs gurus out there on usage of promises. 寻求有关使用承诺的nodejs专家的帮助。 I have the following test program, in which I invoke an async "q" function that simply throws an exception.
我有以下测试程序,其中我调用一个简单抛出异常的异步“q”函数。 This program leaks memory pretty consistently;
这个程序非常一致地泄漏内存; but the leak goes away if uncomment the .done() call.
但如果取消注释.done()调用,泄漏就会消失。
Why does the leak happen when the promise is unterminated (ie no done() call)? 为什么在未终止承诺时发生泄漏(即没有完成()调用)? I tried to follow the documentation , but have trouble understanding the explanation of the done() method.
我试图遵循文档 ,但无法理解done()方法的解释。 Thanks in advance for your help!
在此先感谢您的帮助!
Here's my code: 这是我的代码:
(function() {
var MAX_ITER_COUNT, Q, iterCount, maxMem, noop, qDoit, test;
Q = require("q");
iterCount = 0;
MAX_ITER_COUNT = 10 * 1000;
maxMem = 0;
noop = function() {};
qDoit = function() {
var currentMem;
currentMem = Math.round(process.memoryUsage().heapUsed / 1024 / 1024);
if (currentMem > maxMem) {
maxMem = currentMem;
}
console.log("" + iterCount + " - memory is: " + currentMem + "/" + maxMem + " MB");
return Q(10).then(function() {
throw new Error("X");
});
};
test = function() {
if (iterCount++ > MAX_ITER_COUNT) {
console.log("DONE");
return;
}
// ---- If I uncomment the done() call below the leak goes away ----
return qDoit()["finally"](function() {
return setImmediate(test);
})
//.done(noop, noop, noop);
};
Q.onerror = function() {};
test();
}).call(this);
Answering my own question, hopefully it will help someone. 回答我自己的问题,希望它会帮助某人。
On digging a bit into the q
library code, it looks like all unhandled exceptions are put in an array called unhandledRejections
, by default. 在对
q
库代码进行挖掘时,默认情况下看起来所有未处理的异常都放在一个名为unhandledRejections
的数组中。 Not sure why it was implemented like this, but presumably to help developers track down un-handled exceptions. 不知道为什么它是这样实现的,但可能是为了帮助开发人员追踪未处理的异常。 This behavior can be changed by calling
Q.stopUnhandledRejectionTracking()
. 可以通过调用
Q.stopUnhandledRejectionTracking()
来更改此行为。 When I did this, the memory leak went away, even without the .done()
call. 当我这样做时,即使没有
.done()
调用,内存泄漏也会消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.