2012-11-30 81 views
1

我試圖縮小與我的node.js服務器有關的內存問題的潛在原因。我一直感到有點不舒服的一部分代碼是我使用Q的承諾。Node.js與Q :: Q.ninvoke承諾

這裏是我的基本結構是什麼樣子:

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,該怎麼辦?一切都在這裏正確的範圍?

回答

3

這對我來說看起來很穩固。只要它暴露Node.js回調API(例如,通過nodeify;請參閱最近更新的API reference),this.doSomethingElse使用promise就沒有問題。

-

這就是說,我會重寫你的函數如下:

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

糾正我,如果我錯了,但Q.all意味着異步執行。我沒有在我的示例中明確指出我需要按順序運行,但通常我的第二個函數依賴於第一個函數的結果。事實如此,我的例子就是「最好的方式?」還是有更好的? –

+0

承諾本質上具有異步執行,所以我不確定你的意思。 對於依賴第一個結果的第二個函數,'then'確實是正確的選擇。包括的例子。 – Domenic