Node.js使用Q :: Q.ninvoke链承诺

我试图缩小与我的node.js服务器有关的内存问题的潜在原因。 我一直感到有点不舒服的一部分代码是我使用Q的承诺。

以下是我的基本结构:

var Q = require('q'); MyClass.prototype.doSomething = function(somedata, callback) { var res = [];// will contain the results of each function call Q.ninvoke(this, 'doSomethingElse', 'hello!') .then((function(result){ res.push(result); return Q.ninvoke(this.someobject, 'someFunction', somedata); }).bind(this)) .then((function(result){ res.push(result); callback(null, res);// Returns both result objects, in an array }).bind(this)) .fail(callback) .done(); } 

这看起来合乎逻辑吗?

如果doSomethingElse函数也使用promise,该怎么办? 这里的一切都是正确的吗?

这对我来说看起来相当坚固。 只要它暴露了一个Node.jscallbackAPI(例如,通过nodeify ;请参阅最近更新的API参考 ),使用promises的this.doSomethingElse没有任何问题。

这就是说,我会重写你的function如下:

 MyClass.prototype.doSomething = function(somedata, callback) { return Q.all([ Q.ninvoke(this, 'doSomethingElse', 'hello!'), Q.ninvoke(this.someobject, 'someFunction', somedata) ]).nodeify(callback); }; 

如果你在第二个函数依赖于第一个函数的结果的情况下,我不会这样做

 MyClass.prototype.doSomething = function(somedata, callback) { return Q.ninvoke(this, 'doSomethingElse', 'hello!').then(function (result) { return Q.invoke(this.someobject, 'someFunction', result); }.bind(this)) .nodeify(callback); }; 

或者可能

 MyClass.prototype.doSomething = function(somedata, callback) { var doSomethingElse = Q.nfbind(this.doSomethingElse.bind(this)); var someFunction = Q.nfbind(this.someobject.someFunction.bind(this.someobject)); return doSomethingElse('hello!').then(someFunction).nodeify(callback); }; 

更一般地说:我们最近一直在研究Q性能和内存,结果主要在未发布的主分支。 尤其是:

  • 0.8.11 修复了一个相当可怕的内存泄漏相关的长堆栈痕迹
  • 大师用Q.reject修复一个小内存泄漏
  • Master不再使用V8中速度较慢的 Object.freeze
  • 大师添加closures长堆栈跟踪的能力。