Nodejs – 承诺,未处理的终止和内存泄漏

寻求有关使用promise的nodejs专家的帮助。 我有以下testing程序,其中我调用asynchronous“q”函数,只是抛出一个exception。 这个程序相当一致地泄漏内存; 但如果取消注释.done()调用,则泄漏消失。

为什么泄漏发生在承诺未终止(即没有完成()调用)? 我试图按照文档 ,但无法理解done()方法的解释。 在此先感谢您的帮助!

这是我的代码:

(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); 

回答我自己的问题,希望能帮助别人。

在深入研究q库代码时,它看起来像所有未处理的exception都放在一个名为unhandledRejections的数组中,默认情况下。 不知道为什么它是这样实现的,但大概是为了帮助开发人员追踪未处理的exception。 通过调用Q.stopUnhandledRejectionTracking()可以更改此行为。 当我这样做时,内存泄漏消失,即使没有.done()调用。