Node.js Promises with Q :: Q.ninvoke chains

I'm trying to narrow down the potential causes of memory issues I'm having with my node.js server. One part of the code that I've always been a bit uncomfortable with is my use of Q promises.

Here's what my basic structure looks like:

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

Does this seem logical?

What if the doSomethingElse function also employs promises? Is everything scoped properly here?

This looks pretty solid to me. There's no problem with this.doSomethingElse using promises, as long as it exposes a Node.js callback API (e.g. via nodeify; see recently-updated API reference).

--

That said, I would rewrite your function as follows:

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

if you were in a case where the second function depended on the result of the first, unlike the one given here, I'd do

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

or maybe

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

--

More generally: we've recently been working on Q performance and memory, with the results mostly in the unreleased master branch. In particular: