我正在尝试缩小 Node.js 服务器内存问题的潜在原因。我一直对代码中 Q Promise 的使用感到有点不舒服。
这是我的基本结构:
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 会怎样?这里的一切范围都正确吗?
最佳答案
这对我来说看起来很可靠。使用 Promise 的 this.doSomethingElse
没有问题,只要它公开 Node.js 回调 API(例如通过 nodeify
;请参阅最近更新的 API reference )。
--
也就是说,我将重写你的函数如下:
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 fixed a rather horrible memory leak与长堆栈跟踪相关
- 大师fixes a small memory leak with
Q.reject
- Master 不再使用
Object.freeze
,即 slow in V8 - Master 将能力添加到 turn off long stack traces .
关于Node.js 使用 Q::Q.ninvoke 链进行 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13653286/